Thanos Tip Thanos Tip - 5 months ago 15
PHP Question

Remove everything else from an image link but keep src

I am trying to remove some atrtibutes from images but it removes only the name of atribute and keep the rest..

i have an image as shown bellow:

<img class="aligncenter size-full wp-image-sd174" src="http://www.blahblah.com/wp-content/uploads/2016/06/07d333r.jpg" alt="alt title" srcset="http://www.blahblah.com/wp-content/uploads/2016/06/07d333r.jpg 700w, http://www.blahblah.com/wp-content/uploads/2016/06/07d333r.jpg 241w, http://www.blahblah.com/wp-content/uploads/2016/06/07d333r.jpg 624w" sizes="(max-width: 700px) 100vw, 700px" height="870" width="700">


I want to remove everything except
<img src="image path">


i tried the code bellow but it removes only the name of atribute.. for e.g srcset.

$html = "<img class="aligncenter size-full wp-image-sd174" src="http://www.blahblah.com/wp-content/uploads/2016/06/07d333r.jpg" alt="alt title" srcset="http://www.blahblah.com/wp-content/uploads/2016/06/07d333r.jpg 700w, http://www.blahblah.com/wp-content/uploads/2016/06/07d333r.jpg 241w, http://www.blahblah.com/wp-content/uploads/2016/06/07d333r.jpg 624w" sizes="(max-width: 700px) 100vw, 700px" height="870" width="700">";

$one = preg_replace('#(<img.+?)srcset=(["\']?)\d*\2(.*?/?>)#i', '$1$3', $html);
$two= preg_replace('#(<img.+?)sizes=(["\']?)\d*\2(.*?/?>)#i', '$1$3', $one);

Answer

Try this:

$html = preg_replace("/(<img\\s)[^>]*(src=\\S+)[^>]*(\\/?>)/i", "$1$2$3", $html);

It doesn't replace the unnecessary attributes, it extracts the src attribute with the opening and closing of the image tag.

It should work for any number of <img> tags in your html.