简体   繁体   中英

use preg_replace to replace whole words using associative array

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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