regex - php - need a regular expression to find and append website url to img src -


this question has answer here:

i have got search within html message image tags , append website url image url tag found using regular expression

e.g if image src in html message

/images/my_image.jpg 

i need append url , make this:

http://mywebsite.com/page/images/my_image.jpg 

you should use html parsing solution instead of regex, avoid surprises badly formatted code. this:

// example source $source = <<<eos <html><body>     images have host appended:     <img src="foo.png" />     ,     <img src="images/en/87a%20-zzq.png" />      image left is:     <img src="https://www.gravatar.com/avatar/1b1f8ad9a64564a9096056e33a4805bf?s=32&amp;d=identicon&amp;r=pg" /> </body></html> eos;  // create dom document , read html $dom = new domdocument(); $dom->loadhtml($source);  // use xpath query find 'img' tags  $xpath = new domxpath($dom); $images = $xpath->query('//img');  // loop through tags foreach ($images $image) {     // grab 'src' attribute     $src = $image->getattribute('src');      // if attribute not contain scheme (e.g. http(s)),     // append url scheme , host     if ($src && (!parse_url($src, php_url_scheme))) {         $image->setattribute('src', "http://mywebsite.com/page/" . $src);     } }  // write output $dom->formatoutput = true; echo $dom->savehtml(); 

output:

<!doctype html public "-//w3c//dtd html 4.0 transitional//en" "http://www.w3.org/tr/rec-html40/loose.dtd"> <html><body>         images have host appended:         <img src="http://mywebsite.com/page/foo.png">         ,         <img src="http://mywebsite.com/page/images/en/87a%20-zzq.png">          image left is:         <img src="https://www.gravatar.com/avatar/1b1f8ad9a64564a9096056e33a4805bf?s=32&amp;d=identicon&amp;r=pg"> </body></html> 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -