正则表达式匹配类似 bbcode 的标签之间的内容

我正在研究 bbcodes(基本上是 Wordpress 短代码)的自定义实现。为此,我需要匹配两个类似 bbcode 的标签之间的内容。


例如:


[example]The content I want to retrieve[/example]

问题是这些标签基本上可以是任何东西。这次可能是个例子,但很可能是这样的:


[hello_world with="attribute"]And some [more-complex] content[/hello_world]

我唯一需要的是 hello_world 短代码中更复杂的内容。我找到了一个实现此目的的正则表达式,我对其进行了一些修改以满足我的需要:


(?<=\[.*\])(.*?)(?=\[.*\])

但是在下面的代码中使用时:


<?php

$tag = '[test_tag with="attributes"]Content I [want] To capture[/test_tag]';


// Get the content of the shortcode.

preg_match('~(?<=\[.*\])(.*?)(?=\[.*\])~', $tag, $shortcodeContent);

var_dump($shortcodeContent);

我收到以下错误:


Warning: preg_match(): Compilation failed: lookbehind assertion is not fixed length at offset 10 

是否有一种简单的方法来修复此错误?我知道发生这种情况是因为我使用了长度未指定的“全部捕获”模式。但是我对如何真正解决这个问题感到困惑。(我不是真的不是正则表达式向导)


幕布斯6054654
浏览 132回答 1
1回答

莫回无

如果我没有误解您的问题,那么您可以通过这种方式使用此正则表达式捕获内部文本内容。<?php$re = '/(?<=\])(.*?)(?=\[\/)/m';$str = '[test_tag with="attributes"]Content I [want] To capture[/test_tag]';preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);// Print the entire match resultecho $matches[0][0];?>工作演示:&nbsp;https ://3v4l.org/qgcNg
打开App,查看更多内容
随时随地看视频慕课网APP