开发者

PHP Regular expression tag matching

Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

[template option="whatever"] 

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

[/template]

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

> /\[template\s*option=["\开发者_Python百科']([^"\']+)["\']\]((?!\[\/template\]))/

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris


edit: [\s\S] will match anything that is space or not space.

you may have a problem when there are consecutive blocks in a large string. in that case you will need to make a more specific quantifier - either non greedy (+?) or specify range {1,200} or make the [\s\S] more specific

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


Try this

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

basically instead of using complex regex to match every single thing just use (.*) which means all since you want everything in between its not like you want to verify the data in between


The assertion ?! method is unneeded. Just match with .*? to get the minimum giblets.

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


Chris,

I see you've already accepted an answer. Great!

However, I don't think use of regular expressions is the right solution here. I think you can get the same effect by using string manipulations (substrings, etc)

Here is some code that may help you. If not now, maybe later in your coding endeavors.

<?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";

?>

Hope this helps anyone looking for a similar answer with a different flavor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜