lemmin Posted November 18, 2008 Share Posted November 18, 2008 With this string: <?php "<img src=\"1.jpg\" /><img src=\"2.jpg\" alt=\"2\" />" ?> I am trying to add a string like "alt=\"1\"" to only the img tag that does NOT already have an alt property This regex matches the src property just like I want it to: "/(<\s*img\s*src\s*=\s*[\"|'](.+?)[\"|'])/" But when I try to match the end tag without any other characters, it gets greedy and matches the quote from the end of the alt property: "/(<\s*img\s*src\s*=\s*[\"|'](.+?)[\"|'])\s*\/>/" So, is there a way to implement this regex where the .+? won't match the middle quotes? Or, what is a good way to match the img tag that doesn't have an alt property? I know I could do it with two statements, but it seems like it should be possible with just one. Thanks. Quote Link to comment Share on other sites More sharing options...
lemmin Posted November 18, 2008 Author Share Posted November 18, 2008 I guess I should have thought about this harder, I just figured it out: "/(<\s*img\s*src\s*=\s*[\"|']([^\"]*?)[\"|'])\s*\/?>/" Quote Link to comment Share on other sites More sharing options...
effigy Posted November 18, 2008 Share Posted November 18, 2008 <pre> <?php $data = '<img src="1.jpg" /><img src="2.jpg" alt="2" />'; echo( htmlspecialchars( preg_replace('%<img\s+((??!alt=)[^>])*?)\s*/?>%', '<img $1 alt="1" />', $data) ) ); ?> </pre> Quote Link to comment Share on other sites More sharing options...
lemmin Posted November 18, 2008 Author Share Posted November 18, 2008 Yeah, I realized that regex would only work for the strict syntax that my input was using. This would be a more universal way of matching any img tag without an alt property: /<\s*img(.(?!alt\s*=\s*['\"]))+?\/?>/ Thanks for the help. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.