PHP Regex to grab {tag}something{/tag}
I'm trying to come=up with a regex string to use with the PHP preg functions (preg_match, etc.) and am stumped on this:
How do you match this string?:
{area-1}some text and maybe a <a href开发者_StackOverflow="http://google.com">link</a>.{/area-1}
I want to replace it with a different string using preg_replace.
So far I've been able to identify the first tag with preg_match like this:
preg_match("/\{(area-[0-9]*)\}/", $mystring);
Thanks if you can help!
If you don't have nested tags, something this simple should work:
preg_match_all("~{.+?}(.*?){/.+?}~", $mystring, $matches);
Your results can be then found in $matches[1]
.
I would suggest
preg_match_all("~\{(area-[0-9]*)\}(.*?)\{/\1\}~s", $mystring, $matches);
This will even work if other tags are nested inside the area
tag you're looking at.
If you have several area
tags nested within each other, it will still work, but you'll need to apply the regex several times (once for each level of nesting).
And of course, the contents of the matches will be in $matches[2]
, not $matches[1]
as in Tatu's answer.
精彩评论