You could use explode();
on src=
and then trim off the remaining =
and the "
at each end if you don't want them:
<?php
$string = '<img style="max-width:100%" src="http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png" alt="">';
$string = explode("src=", $string);
$string = explode(" ", $string[1]);
$string = substr($string[0], 1, -1); // remove 1st and last "
echo $string;
?>
You will need to be sure that your HTML has no single inverted commas and escape them if it does like this \'
Last line to remove first and last character borrowed from @SeanBright 's answer here: Delete first character and last character from String PHP
$string = explode('src=', $string);
works - tested. Then you only need to remove the " "
afterwards with $string = substr($string[0], 1, -1); // remove 1st and last "
.
You could also remove both of the double inverted commas with
$string = str_replace('"','',$string);
I think your regex is failing because it is just getting everything after the src=" but not stopping at the space. Others have commented elsewhere that regex is not the most reliable way to split up HTML.
If you don't want explode();
you could split the string using strpos()
and substr();
$string = '<img style="max-width:100%" src="http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png" alt="">';
$pos = strpos($string,'http');
$string = substr($string,$pos, -9); // remove last " and alt-...
echo $string;
This will only work if the end of the image tag is as yours but would fail if the tag close />
was there so you would need to use a bit more code to make that fully programmatic:
$string = '<img style="max-width:100%" src="http://media.doisongphapluat.com/thumb_x670x/2015/12/26/thumon.png" alt="">';
$pos = strpos($string,'http'); // find position of !http!
$string = substr($string,$pos); /// get string after !http"
$len = strlen($string); // get the length of resulting string
$pos1 = strpos($string,'"'); // find last "
$difpos = $len - $pos1; // get the difference to use for the minus
$string = substr($string,0,-$difpos); // get the string from 0 to "minus" position at end.
echo $string;