faqts : Computers : Programming : Languages : PHP : Common Problems : Regular Expressions

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 9 people (78%) answered Yes
Recently 6 of 8 people (75%) answered Yes

Entry

How can I replace the first occurance of cat with cat1, second occurance of cat with cat2 and so on using ereg_replace or str_replace?

Dec 1st, 2003 12:41
Jakub Vrana, Dalton Hunter,


Take a look at function preg_replace_callback().
<?php
function add_numbers($matches) {
	static $i = 0;
	$i++;
	return $matches[0] . $i;
}
echo preg_replace_callback("/cat/", "add_numbers", "a cat b cat c 
cat");
// prints: a cat1 b cat2 c cat3
?>