2013-07-31 39 views
0

基本上我都存儲在$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。任何想法爲何如此?

+1

移動's2'更換。 –

+0

這樣做可以讓's'單獨失敗 –

+0

這有點奇怪。什麼是確切的輸出?這聽起來好像你的替換數組中的最後一個元素沒有被執行。 –

回答

2

移動s2更換s替換之前。

既然你是在做一次更換一個,你正在破壞s2它得到一個機會來取代它之前。

3.20米/秒2將被轉化這樣

[米]3.20米/ S2

[秒]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) 
了`s`替換之前
+0

實際上在提交上提到,如果移動的S2運作良好,並給出meterpersecondsquare,然而對於米/秒它不再工作,並給出米,我試圖改變替換變種從S2->秒到秒2 - >秒在最後的輸出之後,但不能工作...... –

+1

@FaouziNikolaic,我更新了正確的順序。你的其他改變不起作用的原因是因爲字符串會從'm/s'轉換爲'meters/s'到'meterspers',因爲它不再是一個人,如果它離開末尾,它將不再是單獨的。 –

+0

非常感謝,讓一切正常工作! (問題秩序的道德總是重要的) –