Convert Image hyperlink into <img> with PHP
I have this block of code that has a URL to an image. How can convert that into tag with the src? here is the sample code
<div class="field-items">
<div class="field-item odd"><a type开发者_StackOverflow中文版="image/jpeg; length=72486" href="http://www.xyz-website.com/files/263780_147936011949340_128540677222207_316406_533387_n.jpg">263780_147936011949340_128540677222207_316406_533387_n.jpg</a></div></div>
So from the above code, I want to convert that into something like this
<div><img src="http://www.xyz-website.com/files/263780_147936011949340_128540677222207_316406_533387_n.jpg"/><div>
I also want to do this for a particular domain. in the example above its xyz-website.com
Thank you.
Here is the code you need. You will want to modify it to be more specific to your needs. But this uses a regular expression to help extract the image path and saves all found images to an array that you can then use to output it.
$str = '<div class="field-items"><div class="field-item odd"><a type="image/jpeg; length=72486" href="http://www.xyz-website.com/files/263780_147936011949340_128540677222207_316406_533387_n.jpg">263780_147936011949340_128540677222207_316406_533387_n.jpg</a></div></div>';
preg_match('/href="(.)+"/', $str, $matches);
$image_extensions = array('.jpg', '.bmp', '.png');
foreach ($matches AS $match)
foreach ($image_extensions AS $ext)
if (stristr($match, $ext . '"')) //I add the double-quote to the string to signify the end of the href param and prevent string detection confusion
$images[] = str_replace(array('href="', '"'), '', $match);
foreach ($images AS $image)
echo "<div><img src='$image'/><div>";
use regex.
preg_replace('~<div class="field-item odd"><a type="image/jpeg; length=72486" href="(.+?)">(?:.+?)</a></div></div>~i', '<div><img src="$1"/><div>', $str);
something like this
You could explode the a tag and grab the info you want:
$all_html = '263780_147936011949340_128540677222207_316406_533387_n.jpg'; $tmp1 = explode('href="', $all_html); $tmp2 = explode('"', $tmp1[1]); $image_url = $tmp2[0]; if (strpos($image_url, 'xyz-website.com') > -1) { //only output image if the url of the image includes 'xyz-website.com' echo ''; }
精彩评论