使用正则表达式提取第一个“]”和最后一个“[”之间的内容


Extract content between first "]" and last "[" using regex?

是否有可能有一个 PHP 正则表达式将内容从第一个 ] 提取到最后一个 [?

例如,如果我有以下字符串:

$string = [shortcode]You write a shortcode by using ([])[/shortcode]

我想提取:

You write a shortcode by using brackets ([])

并将其存储在变量中。 要提取的内容可以是任何内容。提前谢谢。

您应该使用捕获组来确保与结束标记匹配。

'[('w+)'].*?'[/'1']

这将匹配[]中的一个单词并继续下去,直到如果在[/...]中找到相同的单词。

正则表达式默认是贪婪的,所以这将很好地完成这项工作:

/'](.*)'[/

要使其在 PHP 中正常工作,您可以执行以下操作:

preg_match('/'](.*)'[/', $text, $matches);
$result = $matches[1];

这可以让你需要什么

[^']]'](.*)'[[^'[]

这有效:

preg_match( '@'](.*)'[@', $string, $matches);
print_r($matches);
相关文章: