PHP - 正则表达式不一致

时间:2012-12-12 16:37:59

标签: php regex

我有以下声明

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

我无法弄清楚如何在所有情况下使用带有上标的标签来围绕th,rd,st或nd。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

[0-z]还包含以下符号::;<=>?@[]^_`

值得注意的是,<已包含在内。

请尝试[^[:alnum:]]

编辑:另外,为什么不把它作为一个先行?

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

然后你可以在替换字符串中使用$0