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($pat tern, 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.
[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($pat
This however will only match if caption is the first attribute.
Any solution to this would be very much appreciated.
Thanks.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
ASKER
Thanks for your help.
ASKER