SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2001
    Posts
    31
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP equivalent to Perl's $` and $' ?

    Hi,

    preg_match() allows you to pass an array that gets stuffed with the matches for each parenthesized subpattern. However, what I'd like to know is whether I can also get at the text before the matched text and the text after the matched text, like the Perl $` and $' operators. Is there some standard way to do this in PHP. I didn't see any way to do this after a couple of looks through the preg chapter in the PHP manual; I'm hoping I missed something.

    Thanks

  2. #2
    epsilon transition cupid's Avatar
    Join Date
    Aug 2001
    Location
    Kent, Ohio
    Posts
    367
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I've been wondering this myself. Unfortunately, I really don't think PHP has these special variables. I agree that it'd be nice. This could be a possible workaround. We'll name this function ppMatch:

    Say you're doing a search for anything in between percentage signs: /%.*%/

    PHP Code:

    <?php

    function ppMatch($matchString,$string,$pp) {
        
    $splitTok split($matchString$string);
        return 
    $splitTok[$pp];
    }

    //example of usage
    $searchString "%.*%";
    $string "lalala %asdfasdf blah% asdfasdfasdf";

    if (
    preg_match("/$searchString/"$string)) {
      echo 
    ppMatch($searchString,$string,0); //same as echo $`
      
    echo ppMatch($searchString,$string,1); //same as echo $'

    }

    ?>

  3. #3
    SitePoint Enthusiast
    Join Date
    Sep 2001
    Posts
    31
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Will this works for all cases, I mean just like the Perl $` and $' operators?

    How can I do the same thing but this time with $& operator?

    Thank you for all your help.
    Thanks

  4. #4
    epsilon transition cupid's Avatar
    Join Date
    Aug 2001
    Location
    Kent, Ohio
    Posts
    367
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Originally posted by faithlezz
    Will this works for all cases, I mean just like the Perl $` and $' operators?
    It should, yes.

    How can I do the same thing but this time with $& operator?
    $&, being the match variable, is covered in PHP. Here's what you'd do:

    PHP Code:
    //notice the third parameter, $match
    if (preg_match("/$searchString/"$string$match)) {
      echo 
    $match[0]; //First string matched
      
    echo $match[1]; //Second string matched
      /* ...and so on... */



Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •