Preg_replace无法正常工作

时间:2013-07-31 17:01:45

标签: php regex preg-replace

基本上我在$text var:

中存储了以下文本
$text = 'An airplane accelerates down a runway at 3.20 m/s2 for 32.8 s until is finally lifts off the ground. Determine the distance traveled before takeoff'.

我有一个函数用一个名为$replacements的数组取代文本中的一些关键字,这是(我对它做了一个var_dump):

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

该文本通过以下功能:

$toreplace = array_keys($replacements);

foreach ($toreplace as $r){
    $text = preg_replace("/\b$r\b/u", $replacements[$r], $text);
}

然而,我期望与输出之间存在差异:

Expected Output : an airplane accelerates down runway at 3.20 meterpersecondsquare for 32.8 second until finally lifts off ground determine distance traveled before takeoff 

Function Output : an airplane accelerates down runway at 3.20 meterpers2 for 32.8 second until finally lifts off ground determine distance traveled before takeoff 

请注意,我希望'meterpersecondsquare'并且我得到'meterpers2'('s2'未被替换),而'm'和'/'被替换为它们的值。

我注意到当我把m / s而不是m / s2时,它工作正常并给出:

an airplane accelerates down runway at 3.20 meterpersecond for 32.8 second until finally lifts off ground determine distance traveled before takeoff 

所以问题基本上与s2不匹配。有什么想法是这样的吗?

1 个答案:

答案 0 :(得分:2)

s2替换之前移动s替换。

由于您正在进行一次替换,因此在有机会替换它之前,您正在销毁s2

3.20 m / s2 将会像这样转换

  

[m] 3.20米/秒

     

[s] 3.20米/秒2

     

[/] 3.20 meterpersecond2

这导致 meterpersecond2

这是正确的顺序

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