开发者

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜