With PHP, how can I isolate the contents of the src attribute from $foo? The end result I\'m looking for would give me just \"http://example.com/img/image.jpg\"
<?php
$foo = '<img class="foo bar test" title="test image" src="http://example.com/img/image.jpg" alt="test image" width="100" height="100" />';
$array = array();
preg_match( '/src="([^"]*)"/i', $foo, $array ) ;
print_r( $array[1] ) ;
http://example.com/img/image.jpg
lets assume i use
$text ='<img src="blabla.jpg" alt="blabla" />';
in
getTextBetween('src="','"',$text);
the codes will return :
blabla.jpg" alt="blabla"
which is wrong, we want the codes to return the text between the attribute value quotes i.e attr = "value".
so
function getTextBetween($start, $end, $text)
{
// explode the start string
$first_strip= end(explode($start,$text,2));
// explode the end string
$final_strip = explode($end,$first_strip)[0];
return $final_strip;
}
does the trick!.
Try
getTextBetween('src="','"',$text);
will return:
blabla.jpg
Thanks all the same , because your solution gave me an insight to the final solution .
try this pattern:
'/< \s* img [^\>]* src \s* = \s* [\""\']? ( [^\""\'\s>]* )/'
preg_match
solves this problem nicely.
See my answer here: How to extract img src, title and alt from html using php?