PHP正则表达式标记匹配

时间:2011-01-23 03:50:36

标签: php regex

在试图让这个工作起作用的时候,我的头撞到了墙上 - 非常感谢任何正则表达式专家的帮助!

必须匹配的文字

[template option="whatever"] 

<p>any amount of html would go here</p>

[/template]

我需要提取'option'值(即'what')和模板标签之间的html。

到目前为止,我有:

> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/

除了模板标签之间的html之外,其他所有内容。

有什么想法吗?

谢谢,克里斯

4 个答案:

答案 0 :(得分:1)

试试这个

/\[template\s*option=\"(.*)\"\](.*)\[\/template]/

基本上没有使用复杂的正则表达式匹配每一件事只需使用(。*)这意味着所有因为你想要的一切都在它之间而不是你想要验证之间的数据

答案 1 :(得分:1)

编辑:[\ s \ S]将匹配任何空格或非空格。

当大字符串中有连续的块时,您可能会遇到问题。在这种情况下,你需要制作一个更具体的量词 - 非贪婪(+?)或指定范围{1,200}或使[\ s \ S]更具体

/\[template\s*option=["\']([^"\']+)["\']\]([\s\S]+)\[\/template\]/

答案 2 :(得分:0)

断言?!方法不需要。只需与.*?匹配即可获得最低限度的内脏。

/\[template\s*option=\pP([\h\w]+)\pP\]  (.*?)  [\/template\]/x

答案 3 :(得分:0)

克里斯,

我知道你已经接受了答案。太好了!

但是,我不认为使用正则表达式是正确的解决方案。我认为通过使用字符串操作(子串等)可以获得相同的效果

以下是一些可能对您有所帮助的代码。如果不是现在,可能在您的编码工作中稍后。

<?php

    $string = '[template option="whatever"]<p>any amount of html would go here</p>[/template]';

    $extractoptionline = strstr($string, 'option=');
    $chopoff = substr($extractoptionline,8);
    $option = substr($chopoff, 0, strpos($chopoff, '"]'));

    echo "option: $option<br \>\n";

    $extracthtmlpart = strstr($string, '"]');
    $chopoffneedle = substr($extracthtmlpart,2);
    $html = substr($chopoffneedle, 0, strpos($chopoffneedle, '[/'));

    echo "html: $html<br \>\n";

?>

希望这有助于任何寻找具有不同风味的类似答案的人。

相关问题