开发者

Replacing a sequence in a string with its match index

开发者 https://www.devze.com 2023-01-31 09:16 出处:网络
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.

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

精彩评论

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

关注公众号