使用preg_replace使用关联数组替换整个单词 [英] use preg_replace to replace whole words using associative array
本文介绍了使用preg_replace使用关联数组替换整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为$initialdata
的替换数组:
I have this replacement array named $initialdata
:
array ($initialdata)
'd' => string '1.40' (length=4)
'a' => string '1.67' (length=4)
'vi' => string '0' (length=1)
't' => string '?' (length=1)
然后我有这个字符串:
$str = "-(vi + sqrt(2*a*d + vi^2))/a)";
我这样做时:
str_replace(array_keys($initialdata),array_values($initialdata),$str);
我明白了:
-(0 + sqr?(2*1.67*1.40 + 0^2))/1.67)
发生的是,在我的$initialdata
数组上,"sqrt"的"t"被替换为"t"的值.我知道发生这种情况是因为我正在使用str_replace
,并且我需要使用preg_replace
匹配整个单词,但是我从未见过使用关联数组匹配任何整个单词的preg_replace
的任何实现.如果可能的话如何实现?
What happened was that the "t" of the "sqrt" was replaced by the value of "t" on my $initialdata
array. I know that this happens because I'm using str_replace
, and I need to match whole words using preg_replace
, however I never saw any implementation of preg_replace
using associative arrays to match any whole word. How can this be achieved if possible?
推荐答案
在正则表达式中,\b
是单词边界.这应该起作用:
In regex, \b
are the word boundaries. This should work:
$data = array(
'/d/' => '1.40',
'/a/' => '1.67',
'/vi/' => '0',
'/\bt\b/' => '?'
);
$result = preg_replace(array_keys($data), array_values($data), $str);
这篇关于使用preg_replace使用关联数组替换整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文