Preg Match for multiple attributes.
Posted on 2004-11-29
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.