开发者

Replacing a sequence in a string with its match index

In PHP, If I am replacing "a" in a string "a b a b a b c", how do I get it to replace wi开发者_JAVA技巧th the index of the match (i.e. "1 b 2 b 3 b c")?


use preg_replace_callback instead.

PHP 5.3.0 example (not tested):

$i = 0;
preg_replace_callback("/a/", function( $match ) {
    global $i;
    return ++$i;
}, "a b a b a b c");


$str = 'a b a ba a';
$count = 1;
while(($letter_pos = strpos($str, 'a')) !== false) {
    $str = substr_replace($str, $count++, $letter_pos, 1);
}


Are you sure you need preg_*?

Here is how I would do it:

$numerals = range(1, 10);
$str = str_replace('a', $numerals, $str);

The sadly neglected and often ignored str_replace() function can accept arrays as arguments. In case an array is passed as the second argument, it changes every occurrence of the search string with the corresponding array's element.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜