为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
幕布斯6054654 2022-12-30 17:42:52
我正在研究 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 是否有一种简单的方法来修复此错误?我知道发生这种情况是因为我使用了长度未指定的“全部捕获”模式。但是我对如何真正解决这个问题感到困惑。(我不是真的不是正则表达式向导)
查看完整描述

1 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

如果我没有误解您的问题,那么您可以通过这种方式使用此正则表达式捕获内部文本内容。

<?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 result

echo $matches[0][0];

?>

工作演示: https ://3v4l.org/qgcNg


查看完整回答
反对 回复 2022-12-30
  • 1 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号