tags:

views:

82

answers:

3

Hello,

I want to replace only the first matching element in a string instead of replacing every matching element in a string

$str = 'abc abc abc';
$find = 'abc';
$replace = 'def';
echo mb_ereg_replace( $find, $replace, $str );

This will return "def def def".

What would I need to change in the $find or $replace parameter in order to get it to return "def abc abc"?

A: 

Unless you need fancy regex replacements, you're better off using plain old str_replace, which takes $count as fourth parameter:

$str = str_replace($find, $replace, $str, 1);
adam
Hi, I do need fancy regex and it needs to support multi-byte as well.
Mark L
Fair enough. I see a lot of people asking about using preg* functions when they don't need the complexity!
adam
+1  A: 

you can do a mb_strpos() for "abc", then do mb_substr()

eg

$str = 'blah abc abc blah abc';
$find = 'abc';
$replace = 'def';
$m  = mb_strpos($str,$find);
$newstring = mb_substr($str,$m,3) . "$replace" . mb_substr($str,$m+3);
ghostdog74
Thanks for this idea. Ideally I'd like to be able to edit the regex but this could do as an alternative.
Mark L
+1  A: 

Not very elegant, but you could try

$find = 'abc(.*)'; 
$replace = 'def\\1'; 

Note that if your $find contains more capturing groups, you need to adjust your $replace. Also, this will replace the first abc in every line. If your input contains several lines, use [\d\D]instead of ..

Jens
This is perfect, thank you very much!
Mark L