开发者

Only replace first matching element using PHP's mb_ereg_replace

开发者 https://www.devze.com 2022-12-24 06:15 出处:网络
I want to replace only the first matching element in a string instead of replacing every matching element in a string

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 t开发者_如何学编程o change in the $find or $replace parameter in order to get it to return "def abc abc"?


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消