Home >Backend Development >PHP Tutorial >请教关于preg_replace替换的问题

请教关于preg_replace替换的问题

WBOY
WBOYOriginal
2016-06-23 14:39:581002browse

字符串  $str = 'aa__cc__ee';
企图使用这样的语句:  preg_replace('/_{2}?/', array('bb', 'dd'), $str);
替换成  'aabbccddee'
但全部换成了bb,我已经在表达式中加了 ? 号表示非贪婪,希望第一次匹配替换完之后不要再把第二个 __ 双下划线替换了,但发现这样不成功,请问怎么办才好?是不是我对贪婪模式理解错误了呢?


回复讨论(解决方案)

$str = 'aa__cc__ee';$a = array('bb', 'dd');echo preg_replace('/_{2}?/e', 'array_shift($a)', $str);
aabbccddee
不过php5.5已经取消了修饰符“e”,所以还是前瞻点,以免以后改起来麻烦
$str = 'aa__cc__ee';$a = array('bb', 'dd');echo preg_replace_callback('/_{2}?/', function($r) use (&$a) { return array_shift($a); }, $str);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn