Mark L
Mark L

Reputation: 13435

Only replace first matching element using PHP's mb_ereg_replace

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"?

Upvotes: 0

Views: 1398

Answers (3)

Adam Hopkinson
Adam Hopkinson

Reputation: 28795

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, $count);

Upvotes: 0

Jens
Jens

Reputation: 25563

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

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342403

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

Upvotes: 1

Related Questions