Only replace first matching element using PHP's mb_ereg_replace
 
我只想替换字符串中的第一个匹配元素,而不是替换字符串中的每个匹配元素
| 12
 3
 4
 
 | $str = 'abc abc abc';
$find = 'abc';
$replace = 'def';
echo mb_ereg_replace( $find, $replace, $str ); | 
这将返回" def def def"。
 
我需要在$ find或$ replace参数中进行什么更改才能使其返回" def abc abc"?
		
		
- 
第一次出现总是会出现在字符串的开头吗? (我猜不是,但是值得一试!)
- 
嗨,安迪,可能不是,可能在任何地方。 我怀疑find var看起来像这样$ find = [abc] {1};
 
	 
不太优雅,但您可以尝试
| 12
 
 | $find = 'abc(.*)'; $replace = 'def\\\\1';
 | 
请注意,如果$find包含更多捕获组,则需要调整$replace。 同样,这将替换每行中的第一个abc。 如果您的输入包含多行,请使用[\\d\\D]而不是.。
您可以为" abc"做一个mb_strpos(),然后做mb_substr()
 
例如
| 12
 3
 4
 5
 
 | $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); | 
		
		
- 
感谢这个想法。 理想情况下,我希望能够编辑正则表达式,但这可以替代。
 
	 
除非您需要替换正则表达式,否则最好使用普通的str_replace,它以$count作为第四个参数:
 
		
		
- 
嗨,我确实需要漂亮的正则表达式,它也需要支持多字节。
- 
很公平。 我看到很多人在不希望使用preg *函数时就询问它们的复杂性!
- 
那不正确吗? 第四个参数是替换发生的时间。
- 
@Mat-这不是我的回答吗?