Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 正则表达式匹配bbcode类标记之间的内容_Php_Regex - Fatal编程技术网

Php 正则表达式匹配bbcode类标记之间的内容

Php 正则表达式匹配bbcode类标记之间的内容,php,regex,Php,Regex,我正在开发bbcodes的自定义实现(基本上是Wordpress短代码)。为此,我需要匹配两个类似bbcode的标记之间的内容 例如: [example]The content I want to retrieve[/example] 问题是这些标签基本上可以是任何东西。这一次可能是一个例子,但很可能是这样的: [hello_world with="attribute"]And some [more-complex] content[/hello_world] 我唯一需要的是hello_wo

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

例如:

[example]The content I want to retrieve[/example]
问题是这些标签基本上可以是任何东西。这一次可能是一个例子,但很可能是这样的:

[hello_world with="attribute"]And some [more-complex] content[/hello_world]
我唯一需要的是hello_world短代码中更复杂的内容。我发现一个正则表达式可以实现这一点,并对其进行了轻微修改以满足我的需要:

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

有没有一种简单的方法来修复这个错误?我理解之所以会发生这种情况,是因为我使用了长度未指定的“捕获所有”模式。但我有点迷惑不解于如何解决这个问题。(我不是一个真正的正则表达式向导)

如果我没有误解您的问题,那么您可以使用此方法捕获内部文本内容



工作演示:

看一看。出于类似的原因,我鼓励您使用BBCode解析器,而不是尝试拼凑一个正则表达式解决方案。@apokryfos我想学习如何创建自己的基本上模仿短代码的实现(来自Wordpress)。非常感谢你把问题寄给我。这是一本有趣的读物。你是如何通过查找来忽略错误的?我很感兴趣的是如何在将来可能的情况下省略它。@GuylianWasHier在这里查看我的演示正则表达式:@GuylianWasHier很高兴它对您有所帮助:)编码愉快!没有理由在此模式上使用
m
模式修饰符,因为没有锚定(例如
^
$
)。也许你想写
s
pattern修饰符,使点也能与换行符匹配。@mickmackusa是的,先生同意你的意见
<?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 
<?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];
?>