开发者

How to count the number of matches and use it inside of a regular expression?

I am trying to get this result:

<li class="beatle_1">Paul</li> <li class="beatle_2">John</li> <li class="beatle_3">George</li> <li class="beatle_4">Ringo</li>

From this regular expression in PHP:

echo preg_replace('/([\w]+)/','<li 开发者_运维技巧class="beatle_$n">\1</li>','Paul John George Ringo');

But I don't know if it is possible to return the number of matches from inside the regular expression.

I have found something about this on a Perl list:

Janet: "You could put the first result into a variable, then add (concatenate) other results to it after each capture. This also keeps you from depending on $1 (or whatever) later in the program, when it may be rewritten by another regex use."

And Bob Walton:

my $input='a b c d e';
my @output=$input=~/(\w)\s*/g;
print join "\n",@output;

And Jörg Westheide: "That's right, lib pcre doesn't have that. And I also have not (yet) found a way to implement the g modifier in a full Perl compatible way. For details on the problematic stuff see the 'Repeated patterns matching zero-length substring' section in the perlre man page. If that doesn't apply to your problem you should be able to solve your problem with a loop."


With PHP5.3 you can use anonymous function for this.

See this example

echo preg_replace_callback('/([\w]+)/', function ($matches) {
    static $pos = 0;
    return sprintf('<li class="beatle_%d">%s</li>', ++$pos, $matches[1]);
}, 'Paul John George Ringo');


You could try preg_replace_callback() with a closure if you're using PHP 5.3:

$subject = 'Paul John George Ringo';
$n = 0;
echo preg_replace_callback('/([\w]+)/', function($matches) use (&$n) {
    return '<li class="beatle_'.(++$n).'">'.$matches[1].'</li>';
}, $subject);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜