Author Topic: [SOLVED] Matching where something is NOT found  (Read 529 times)

0 Members and 1 Guest are viewing this topic.

Offline lemminTopic starter

  • Addict
  • Posts: 1,651
    • View Profile
[SOLVED] Matching where something is NOT found
« on: November 18, 2008, 02:50:40 PM »
With this string:
Code: [Select]
<?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:
Code: [Select]
"/(<\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:
Code: [Select]
"/(<\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.

Offline lemminTopic starter

  • Addict
  • Posts: 1,651
    • View Profile
Re: Matching where something is NOT found
« Reply #1 on: November 18, 2008, 03:19:51 PM »
I guess I should have thought about this harder, I just figured it out:
Code: [Select]
"/(<\s*img\s*src\s*=\s*[\"|']([^\"]*?)[\"|'])\s*\/?>/"

Offline effigy

  • Staff Alumni
  • Freak!
  • *
  • Posts: 7,301
  • Gender: Male
  • We must be the change we wish to see in the world.
    • View Profile
Re: Matching where something is NOT found
« Reply #2 on: November 18, 2008, 03:35:38 PM »

<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>
Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

Offline lemminTopic starter

  • Addict
  • Posts: 1,651
    • View Profile
Re: Matching where something is NOT found
« Reply #3 on: November 18, 2008, 03:43:59 PM »
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:
Code: [Select]
/<\s*img(.(?!alt\s*=\s*['\"]))+?\/?>/

Thanks for the help.