Regex pattern for shortcodes in PHP

﹥>﹥吖頭↗ 提交于 2019-12-06 02:56:32

In your regex:

\[$shortcode(.+?)?\](?:(.+?)?\[\/$shortcode\])?

The first capture group (.+?) matches at least 1 character.

The whole group is optional, but in this case it happens to match every thing up to the last ].

The following regex works:

\[$shortcode(.*?)?\](?:(.+?)?\[\/$shortcode\])?

The * quantifier means 0 or more, while + means one or more.

Granted this is from C#, but

@"\[([\w-_]+)([^\]]*)?\](?:(.+?)?\[\/\1\])?"

should match any (?) possibly self-closing shortcode.

Or you could steal from wordpress: https://core.trac.wordpress.org/browser/tags/4.0/src/wp-includes/shortcodes.php#L309

$pattern = '/(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
$text = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text);
if ( preg_match_all($pattern, $text, $match, PREG_SET_ORDER) )...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!