Search code examples
phppreg-replace-callback

PHP Output pre_replace_callback


I'm a php coding newbie, I want to output the first and the third matches. The below code is my coding so far.

$string="[nextpage] This is first text
[nextpage] This is the second text
[nextpage] This is the third text";
$string = preg_replace_callback("/\[nextpage\]([^\[nextpage\]]*)(.*?)(\n|\r\n?)/is", function ($submatch) {
    static $matchcount = 0;
    $matchcount++;
    $rtt=$submatch[2];
    return "<li>$rtt</li>";
  }, $string);
echo $string; //This is first text
                This is the second text
                This is the third text

I've tried outputting $rtt=$submatch[0][1]; to get the first match and $rtt=$submatch[0][3]; to get the third match but doesn't work.

Expected results;

//This is first text
  This is the third text

Solution

  • You're not using $matchcount to test which match it is.

    Also, matching \r and \n won't match the end of the last line, since there's no newline after them. You also need to match $, which is the end of the string.

    ([^\[nextpage\]]*) is totally unnecessary, and doesn't do what you probably think it does. [^string] doesn't mean to not match that string, it matches any single character that isn't one of those characters.

    $string = preg_replace_callback("/\[nextpage\]([^\r\n]*)(\n|\r\n?|$)/is", function ($submatch) {
        static $matchcount = 0;
        $matchcount++;
        if ($matchcount == 1 || $matchcount == 3) {
            $rtt=$submatch[1];
            return "<li>$rtt</li>";
        } else {
            return "";
        }
      }, $string);
    

    DEMO