use preg_replace to replace whole words using asso

2019-06-02 07:22发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-02 08:03

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);
查看更多
登录 后发表回答