-
将模式分隔符从
/
到
~
这样你就不用逃避
存在于模式中的字符。
-
-
正则表达式引擎只考虑
]
]
角色。
-
因为你没有使用任何锚(
^
或
$
),的
m
图案修改器是不必要的。
-
i
图案标志/修改器。
-
删除所有多余的捕获组后,只需使用
$1
在替换字符串中。
-
(*SKIP)(*FAIL)
“取消”这些不需要的子字符串。
Demo
)
$bbcodes = [
'Look at this:https://www.example.com/example?ohyeah=sure#okay this is a raw link',
'No attibute bbcode url: [url]http://example.com/x1[/url]',
'A url with link and link text: [url=http://example.com/x2]x2[/url]',
'Image with "ignorable" text: [IMG=sumpthing.jpg]sumpthing[/IMG]',
'Image: [img=sumpinelse][/img]'
];
$search = array (
// ...
'~\[url=((?:ht|f)tps?://[a-z\d.-]+\.[a-z]{2,3}/\S*?)](.*?)\[/url]~i',
'~\[url]((?:ht|f)tps?://[a-z\d.-]+\.[a-z]{2,3}/\S*?)\[/url]~i',
// ...
'~\[img=(.*?)].*?\[/img]~i', // if you want the possibility of dot matching newlines, add s pattern modifier
// ...
'~(?:<a.*?</a>|<img.*?</img>)(*SKIP)(*FAIL)|\bhttps?://.+?(?=\s|$)~im' // mop up any remaining links that are not bbtagged
);
$replace = array (
// ...
'<a href="$1" target="_blank">$2</a>',
'<a href="$1" target="_blank">$1</a>',
// ...
'<img src="$1"></img>',
// ...
'<a href="$0" target="_blank">$0</a>',
);
var_export(preg_replace($search, $replace, $bbcodes));
array (
0 => 'Look at this:<a href="https://www.example.com/example?ohyeah=sure#okay" target="_blank">https://www.example.com/example?ohyeah=sure#okay</a> this is a raw link',
1 => 'No attibute bbcode url: <a href="http://example.com/x1" target="_blank">http://example.com/x1</a>',
2 => 'A url with link and link text: <a href="http://example.com/x2" target="_blank">x2</a>',
3 => 'Image with "ignorable" text: <img src="sumpthing.jpg"></img>',
4 => 'Image: <img src="sumpinelse"></img>',
)