0

基本上我在$textvar 中存储了以下文本:

$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'.

我有一个函数,它从名为 which 的数组中替换文本上的一些关键字$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不匹配。任何想法为什么会这样?

4

1 回答 1

2

s2在更换之前移动s更换。

由于您一次更换一个,因此您在s2有机会更换它之前就将其摧毁。

3.20 m/s2会这样变换

[m] 3.20 米/s2

[s] 3.20 米/秒2

[/] 3.20 米每秒2

这导致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)
于 2013-07-31T17:12:08.673 回答