无法使我的preg_match正常工作

时间:2014-04-08 10:44:17

标签: php regex

我只是继续尝试使用preg_match或preg_match_all进行不同的组合,但我显然很困惑。 这是我使用的代码行:

preg_match ("/(?<=(\[".$tag."\]))(.+)(?=(\[\/".$tag."\]))/s", $text, $matches);

(用于匹配标签内文字的后视和前瞻:[tag](。+)[/ tag]

主题是一个包含如下文本的变量:

[title]Hi this is my title[/title]
[text]some text[/text]
[hidden]some hidden text[/hidden]
[text]again some more text[/text]
[end]end[/end]

现在我试图在[text] [/ text]中只显示文本的不同部分 所以我希望我的回声显示:

some text
again some more text

然而,当我尝试回应我的$ matches(数组)时,我能得到的最好的是:

some text[/text]
[hidden]some hidden text[/hidden]
[text]again some more text

它仅考虑第一个和最后一个标记。我已尝试过其他参数组合,但我只是得到有关偏移的错误等等。

我该怎么办? THX!

3 个答案:

答案 0 :(得分:1)

合并这个简化的正则表达式。 /\['.$tag.'](.*?)\[\/'.$tag.']/

 <?php
 $tag = 'text';  //<--------- Pass the tag name (you can even add title , hidden )
    $str='[title]Hi this is my title[/title]
    [text]some text[/text]
    [hidden]some hidden text[/hidden]
    [text]again some more text[/text]
    [end]end[/end]';

    preg_match_all('/\['.$tag.'](.*?)\[\/'.$tag.']/', $str, $matches);
    print_r($matches[1]);

Demo

<强> OUTPUT :

Array
(
    [0] => some text
    [1] => again some more text
)

enter image description here

答案 1 :(得分:1)

这是因为贪婪的量词:默认情况下,+会尝试尽可能多地使用它。如果您不想这样,请在量词之后添加?以使其不贪婪:

preg_match ("/(?<=([".$tag."]))(.+?)(?=([/".$tag."]))/s", $text, $matches);

这样,点将尝试匹配可能的最小字符数。

正如Shankar Damodaran指出的那样,这里不需要前瞻和后视,所以你不妨写一下:

preg_match ("/\[".$tag."](.+?)(\[\/".$tag."]/s", $text, $matches);

答案 2 :(得分:0)

使用preg_matchall

$input_lines='[title]Hi this is my title[/title]
[text]some text[/text]
[hidden]some hidden text[/hidden]
[text]again some more text[/text]
[end]end[/end]';

preg_match_all("/(?<=\[text\])(.*)(?=\[\/text\])/", $input_lines, $output_array);
print_r($output_array[0]);

输出:

Array
(
    [0] => some text
    [1] => again some more text
)