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