开发者

String replacement

开发者 https://www.devze.com 2023-01-13 04:28 出处:网络
For example i have this string: $test开发者_JS百科_str = \"num Test \\n num Hello \\n num World\";

For example i have this string:

$test开发者_JS百科_str = "num Test \n num Hello \n num World";

And i need to replace these num-s to increasing numbers. like that

"1 Test \n 2 Hello \n 3 World"

How could i do this?


you could use preg_replace_callback

$test_str = "num Test \n num Hello \n num World";

function replace_inc( $matches ) {
    static $counter = 0; // start value
    return $counter++;
}

$output = preg_replace_callback( '/num/', 'replace_inc', $test_str );

Cheers,
haggi


you can do this by substr_count. (php doc

Then loop through your string and, use a counter for the recplace. And put something like echo str_replace("num", $count, $str).


This version works for any number of "num"

<?php
  $num = 2;
  $s = "a num b num c num";

  while(strpos($s, "num") !== false) $s = preg_replace("/num/",$num++,$s,1);

  echo "$s\n";
?>


Variant #1: PHP 5.3+ (anonymous functions)

$count=0;
echo preg_replace_callback('/\bnum\b/',
                           function($v){global $count; return ++$count;},
                           $test_str) ;

Variant #2: regex substitiution eval

$count=0;
echo preg_replace('/\bnum\b/e', '++$count', $test_str); 

Regards

rbo

0

精彩评论

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