Fatih Kahveci
Fatih Kahveci

Reputation: 440

Replace img src and class

I want to change all imgs in the content. I do so by using RegEx.

RegEx:

/<img src="([^\"]+)" class="([^\"]+)"/ig

Content:

<img src="test.jpg" class="qr" />

<img src="test2.jpg" width="230" height="130" class="qr" />

<img src="test3.jpg" style="width:705px" />

This is my problem: the regular expression only matches one time (the first line). But I want to change all src and class attributes.

You can verify this here: http://regexr.com/3asul.

Upvotes: 0

Views: 456

Answers (1)

Sebastian Simon
Sebastian Simon

Reputation: 19485

Your second case has some other attributes within it. You can use .*? inbetween to match that as well:

/<img src=".*?".*? class=".*?"/gi

.*? means any character, at least 0 times, as little as possible.

If you want to replace any img with an src and with an optional class you can wrap the class part in a non-capturing group and use the ? quantifier and then you’d have to add another > to force the RegEx to go to the end of the tag:

/<img src=".*?".*?(?: class=".*?")?>/gi

Upvotes: 2

Related Questions