0

我试过这样做,但我只是不喜欢正则表达式。我需要的是有一个正则表达式,将 1st、3rd 和 9th 替换为 1st、3rd 和 9th,方法任何前面有数字但不后面的 'rd' 'th' 和 'st' 周围添加<sup>包围</sup>通过字母或数字。

4

3 回答 3

5

这是微不足道的,所以我只会给你你需要的组件。

(?<=\d)检查当前位置之前是否存在数字。

(A|B|C)检查当前位置的任何正则表达式 A、B 或 C。

这就是你所需要的。

于 2012-11-17T22:45:08.967 回答
1

试试这个代码:

$string = "bla 1st bla 2nd bla 3rd bla 5th 9thSomethingNotToBeReplaced ";
echo preg_replace('/(\d)+(st|nd|rd|th)([^\w\d]|$)/', '$1<sup>$2</sup>$3', $string);
于 2012-11-17T22:51:26.497 回答
0

我假设你也想处理'2nd':

$string = '1st, 2nd, 3rd and 9th';
echo preg_replace_callback('/1st|2nd|3rd|[4-9]th/', function($m){
    return $m[0]{0} . '<sup>' . substr($m[0], 1) . '</sup>';
  }, $string);

// 1<sup>st</sup>, 2<sup>nd</sup>, 3<sup>rd</sup> and 9<sup>th</sup>
于 2012-11-17T22:50:44.937 回答