Regex pattern for shortcodes in PHP

丶灬走出姿态 提交于 2019-12-07 16:36:33

问题


I have a problem with a regex I wrote to match shortcodes in PHP.

This is the pattern, where $shortcode is the name of the shortcode:

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

Now, this regex behaves pretty much fine with these formats:

  • [shortcode]
  • [shortcode=value]
  • [shortcode key=value]
  • [shortcode=value]Text[/shortcode]
  • [shortcode key1=value1 key2=value2]Text[shortcode]

But it seems to have problems with the most common format,

  • [shortcode]Text[/shortcode]

which returns as matches the following:

Array
(
    [0] => [shortcode]Text[/shortcode]
    [1] => ]Text[/shortcode
)

As you can see, the second match (which should be the text, as the first is optional) includes the end of the opening tag and all the closing tag but the last bracket.

EDIT: Found out that the match returned is the first capture, not the second. See the regex in Regexr.

Can you help with this please? I'm really crushing my head on this one.


回答1:


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.




回答2:


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) )...


来源:https://stackoverflow.com/questions/11346313/regex-pattern-for-shortcodes-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!