tags:

views:

171

answers:

4
+1  Q: 

RegEx teaser

Let's say we have 2 php variables:

The input string of '{@url,<img src="," alt="{@name}" />}' should return:

'<img src="http://domain.com/photo.jpg" alt="caption" />'

The {tag} takes up to 3 parameters: {@variable[,text_before][,text_after]}.

What regex would be needed to make this happen? The tricky part is that a {@..} tag is nested within another.

A: 

Wow, that's mindbendingly hard to read, especially with the quotes appearing within commas.

I'm not sure that a regular expression is the right tool for the job here, especially because of the possible recursion. What other solutions have you considered?

Greg Hewgill
I would second that. The whole concept of yours to express those tag patterns is seriously flawed. I tried to wrap my head around it and you simply *can't* get that to work. For starters, what if the tag values contain curly braces or commas themselves? Try a different approach.
Tomalak
A: 

I don't understand the utility of that syntax, can you explain it? Wouldn't it make more sense to do something like:

<img src="{@url}" alt="{@name}" />

Edit: On another look, it appears this pattern isn't accounting for commas within the template... with that in mind, it would be very easy to explode() on the comma and parse the array from there.

eyelidlessness
A: 

It's for a CMS. Admins can add column fields, then add template code for how it will be displayed on the listing page. The {@tags} are used to output the dynamic column values. This template code:

<p>Link: <a href="{@url}">{@name}</a> - {@date}</p>

would create a listing page like:

Link: link one - 2 July 2008

Link: link two - 14 June 2008

Link: link three - 9 February 2007

...

I figured that people might want to use column values within others, hence the "alt" tag example from the first post. So using regex for this would be a bad idea?

I think your example didn't demonstrate that very well, it looked to me like you could have written it how I did in my answer. Am I mistaken?And yeah, if'n you're separating by commas, $str = explode(',', $str) makes the most sense.
eyelidlessness
+2  A: 

I think you've come across one of those situations where you shouldn't use regex.

much like this one.

http://stackoverflow.com/questions/154708/multi-line-group-and-search-with-regex http://stackoverflow.com/questions/154708/multi-line-group-and-search-with-regex#162194

Keng
To elaborate on that, you can't really parse a recursive syntax reliably with a regular expression. Since this syntax seems to be recursive, a regular expression in this case is probably a mistake.
Ian McLaird