2012-12-12 27 views
-2

我有下面的語句PHP - 正則表達式的作品不一致

echo preg_replace("/(?<=\d)(th|rd|st|nd)([^0-z])/i","<sup>$1</sup>$2","some text 1st<br />\n2nd<br />\n3rd<br />\n4th 5th 21nd 33rd 41st<br />\nsome text"); 

它輸出

some text 1st<br /> 
2nd<br /> 
3rd<br /> 
4<sup>th</sup> 5<sup>th</sup> 21<sup>nd</sup> 33<sup>rd</sup> 41st<br /> 
some text 

我只是無法弄清楚如何使它環繞屆,第三屆,ST或ND在所有情況下都帶上標籤。

+0

究竟是什麼你想要做的,什麼是你期望的輸出是什麼? –

+0

你是什麼'it' – Anirudha

+0

我爲什麼被低估? – L84

回答

1

你可以使用

/(?:\b\d+)(th|rd|st|nd)\b/i 

//boundary \b is required here or else it would also replace within a word 

,取而代之的是

<sup>$1</sup> 
+0

謝謝,現在看起來非常明顯 – L84

+0

實際上,\ b在最後兩行不起作用,但沒有\ b很好用,即使當文字包括像第一第四等字 – L84

+0

@ L84使用適合您的需要的正則表達式..它在'.net'爲我工作..;) – Anirudha

0

[0-z]還包括以下符號::;<=>[email protected][]^_`

值得注意的是,<是包括在內。

嘗試用[^[:alnum:]]代替。

編輯:另外,爲什麼不把它看成是一個超前?

/(?<=\d)(?:th|rd|st|nd)(?=![[:alnum:]])/i 

然後你可以在替換字符串中使用$0

+1

不起作用...我不知道應該怎麼做,即使 – L84