简体   繁体   English

使用preg_replace使用关联数组替换整个单词

[英]use preg_replace to replace whole words using associative array

I have this replacement array named $initialdata : 我有一个名为$initialdata替换数组:

array ($initialdata)
  'd' => string '1.40' (length=4)
  'a' => string '1.67' (length=4)
  'vi' => string '0' (length=1)
  't' => string '?' (length=1)

Then I have this string : 然后我有这个字符串:

$str =  "-(vi + sqrt(2*a*d + vi^2))/a)";

When I do : 当我做 :

str_replace(array_keys($initialdata),array_values($initialdata),$str);

I Get : 我得到:

-(0 + sqr?(2*1.67*1.40 + 0^2))/1.67)

What happened was that the "t" of the "sqrt" was replaced by the value of "t" on my $initialdata array. 发生的事情是“sqrt”的“t”被我的$initialdata数组中的“t”值所取代。 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. 我知道发生这种情况是因为我正在使用str_replace ,我需要使用preg_replace来匹配整个单词,但是我从未看到使用关联数组来匹配任何整个单词的preg_replace任何实现。 How can this be achieved if possible? 如果可能,如何实现?

In regex, \\b are the word boundaries. 在正则表达式中, \\b是单词边界。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM