views:

225

answers:

2

Howdy,

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="http://google.com"&gt;link&lt;/a&gt;.{/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!

+4  A: 

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].

Tatu Ulmanen
What does the `~` character do in this context?
donut
@donut Pattern delimiters indicating the start and end of the pattern. They can be replaced with (afaik) almost any pair of characters. The forward-slash is commonly used.
Mike B
The forward slash is common but awkward if the regex itself contains forward slashes. In that case, the slashes should be escaped, using different characters avoids this.
Tatu Ulmanen
Works perfectly, thanks! How do I include line breaks between tags? It's not matching:{area-1}<h1>something here</h1>{/area-1}(where h1 is on a new line)
Aaron
This works: "~{.+?}(.*?){/.+?}~s" (added s)
Aaron
A: 

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.

Tim Pietzcker
You don't need to escape `{` and `}`, they're interpreted as literal characters unless they're part of a valid token (e.g. {n}). :)
Tatu Ulmanen
I thought so, too, but RegexBuddy had inserted the backslashes for me, so I went with it. Will look into it further.
Tim Pietzcker
Thanks for your help guys. I'll give it a go.
Aaron
Hmmm... couldn't get this one to work for me for some reason.
Aaron