Link to home
Start Free TrialLog in
Avatar of Ape
Ape

asked on

Preg Match for multiple attributes.

I’ve a problem writing a few regular expressions that will all take more or less the same format.  The issue is with recognising the order that words/matches may appear.  Examples of what I am trying to match:

[IMG: XX caption=my caption align=left]

This would be replaced with <img src="myfile.jpg" alt="my caption" align="left"  />

Where myfile.jpg is the image id referenced by XX.

Given that the caption and align attributes might appear in any order I’d like to be able to match on the above or the variation below:

[IMG: XX align=right caption=my caption 2]


In addition, the caption and align attributes are optional and mightn’t necessarily be there at all.

Similarly I am wanting to match the src and align attributes on a standard image html tag:

<img src=”myfile.jpg” align=”left” />

Again the issue here is that the attributes could be anywhere within the image tag itself.

What I have so far:


                        $pattern = '/\[IMG: ([0-9])+ (caption=(.*?)) align=(left|right)]/is'; #match image tags

                        $html_body = preg_replace_callback($pattern, array($this, '_fetchImage'), $html_body);  

This however will only match if caption is the first attribute.

Any solution to this would be very much appreciated.

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of hernst42
hernst42
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Ape
Ape

ASKER

Thanks.  Is there reallly no other way of doing it?  Or at least checking for order of attributes within regualr expressions at all?
with regex it might be possible, but you will need to write all possible occurences into the regex. Even to check sorting must be done the same way. For such a case a parser is needed, one regex will be too complicated, so do it in two passes.
Avatar of Ape

ASKER

Thanks for your help.