php - Preg_replace not working as wanted -
basically have following text stored in $text
var :
$text = 'an airplane accelerates down runway @ 3.20 m/s2 32.8 s until lifts off ground. determine distance traveled before takeoff'.
i have function replaces keywords on text array named $replacements
(i did var_dump on it) :
'm' => string 'meter' (length=5) 'meters' => string 'meter' (length=5) 's' => string 'second' (length=6) 'seconds' => string 'second' (length=6) 'n' => string 'newton' (length=6) 'newtons' => string 'newton' (length=6) 'v' => string 'volt' (length=4) 'speed' => string 'velocity' (length=8) '\/' => string 'per' (length=3) 's2' => string 'secondsquare' (length=12)
the text goes through following function :
$toreplace = array_keys($replacements); foreach ($toreplace $r){ $text = preg_replace("/\b$r\b/u", $replacements[$r], $text); }
however, there difference between expect , output :
expected output : airplane accelerates down runway @ 3.20 meterpersecondsquare 32.8 second until lifts off ground determine distance traveled before takeoff function output : airplane accelerates down runway @ 3.20 meterpers2 32.8 second until lifts off ground determine distance traveled before takeoff
notice expect 'meterpersecondsquare' , 'meterpers2' (the 's2' isn't replaced) while 'm' , '/' replaced values.
i noticed when put m/s instead of m/s2 works fine , gives :
an airplane accelerates down runway @ 3.20 meterpersecond 32.8 second until lifts off ground determine distance traveled before takeoff
so problem doesn't match s2. thoughts why case?
move s2
replacement before s
replacement.
since doing replacement 1 @ time, destroying s2
before gets chance replace it.
3.20 m/s2 transformed this
[m] 3.20 meter/s2
[s] 3.20 meter/second2
[/] 3.20 meterpersecond2
which results in meterpersecond2
here proper order
'm' => string 'meter' (length=5) 'meters' => string 'meter' (length=5) 's2' => string 'secondsquare' (length=12) 's' => string 'second' (length=6) 'seconds' => string 'second' (length=6) 'n' => string 'newton' (length=6) 'newtons' => string 'newton' (length=6) 'v' => string 'volt' (length=4) 'speed' => string 'velocity' (length=8) '\/' => string 'per' (length=3)
Comments
Post a Comment