use preg_replace to replace whole words using associative array

对着背影说爱祢 提交于 2019-12-08 07:53:09

问题


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)

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. 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?


回答1:


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);


来源:https://stackoverflow.com/questions/17979011/use-preg-replace-to-replace-whole-words-using-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!