views:

50

answers:

4

For example i have this string:

$test_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?

A: 

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).

Ben Fransen
Well, i can count `num`-s by substr_count as well. But str_replace will replace all `num`-s in `$str`, so what the point? Or i just don't understand smth?
cru3l
A: 

Hi cru3l,

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

haggi
this exactly what i need
cru3l
Your example would return the numbers off by 1, right? (0,1,2) To answer correctly, you should modify your function to return ++$counter or start with $counter=1
rubber boots
i thought adjusting "// start value" should be easy enough ;)of course, you could also use the prefix-increment which is btw. generally faster, but this could have been a little confusing to somebody who is not that much into programming
haggi
A: 

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";
?>
ring0
A: 

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

rubber boots