基本上我都存儲在$text
VAR以下文字:的preg_replace不工作通緝
$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);
}
但是,與我的期望和輸出端的區別:而「M
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」不會被替換) '和'/'被替換爲它們的值。
我注意到,當我把米/秒代替米/秒,它工作正常,並給出:
an airplane accelerates down runway at 3.20 meterpersecond for 32.8 second until finally lifts off ground determine distance traveled before takeoff
所以問題基本上是不匹配的S2。任何想法爲何如此?
移動's2'更換。 –
這樣做可以讓's'單獨失敗 –
這有點奇怪。什麼是確切的輸出?這聽起來好像你的替換數組中的最後一個元素沒有被執行。 –