PHP preg_replace – 在结果中包含模式/完整主题
发布时间:2020-12-13 16:52:22 所属栏目:PHP教程 来源:网络整理
导读:我有一个问题,我无法解决自己:替换… locale("Sendx","Send")locale("System","System") 应成为: locale("Sendx","Subsub")locale("System","Newsys") 我试过一个简单的替换: $mysearchword = "System"; #changes in a loop$myreplaceword = "Newsys"; #a
我有一个问题,我无法解决自己:替换…
locale("Sendx","Send") locale("System","System") 应成为: locale("Sendx","Subsub") locale("System","Newsys") 我试过一个简单的替换: $mysearchword = "System"; #changes in a loop $myreplaceword = "Newsys"; #also changes in the loop $oneline = str_replace($mysearchword,$myreplaceword,$oneline); 但结果看起来像 locale("Sendx","53ND") locale("Newsys","Newsys") #problem with the doubled word 当然,系统两次都被取代了.所以我决定使用preg_replace $pattern = '/locale(["|']([^"']*)["|'],["|']([^"']*)["|'])/'; $replacement = '${1},Newsys'; $subject = 'locale("System","System")'; echo preg_replace($pattern,$replacement,$subject,-1 ); 但现在几乎没有任何东西丢失,因为只返回括号中的单词而我不知道如何包含该模式或返回替换的$subject. System,Newsys # No idea how to combine $replacement with $pattern... 你能帮我找到合适的结果吗? 解决方法
我想你正在寻找这样的东西:
$input = 'locale("Sendx","Send")'; $output = preg_replace('/,"(.*?)"/',',"Subsub"',$input); echo $output; echo "n"; $input = 'locale("System","System")'; $output = preg_replace('/,"Newsys"',$input); echo $output; 输出: locale("Sendx","Newsys") 模式/,“(.*?)”/在逗号之后搜索双引号之间的单词并替换为“NEW_WORD” 使用此模式,您可以轻松地在循环中替换它们: $input = array( 'locale("Sendx","Send")' => 'Subsub','locale("System","System")' => 'Newsys' ); foreach($input as $string => $replacement) { $output = preg_replace('/,"' . $replacement . '"',$string); echo $output. PHP_EOL; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |