Reputation: 15616
I fetches from value from db like:
<p><img alt="" src="images/1.jpg" style="width: 2450px; height: 1054px;" /></p>
and wants to only get src="images/1.jpg"
but don't know how. Please guide me
Upvotes: 0
Views: 153
Reputation: 268344
If you need the source, use a DOM Parser:
// Construct a new DOMDocument with your fragment
$domDoc = new DOMDocument;
$domDoc->loadHTML( '<p><img src="images/1.jpg" style="width: 2450px;" /></p>' );
// Locate the first image the document
$img = $domDoc->getElementsByTagName( "img" )->item( 0 );
// Echo its src value
echo $img->attributes->getNamedItem( "src" )->nodeValue;
Results: http://codepad.org/oMXGK9Iu
Ideally you would ensure the image elements exist before accessing items #0. Likewise, you would ensure the attributes exist before just leaping out and grabbing them.
Further reading: http://www.php.net/manual/en/class.domdocument.php
If you just want to grab that particular portion of the text, you could use a simple regular expression:
// Prep our html
$html = '<p><img src="images/1.jpg" style="width: 2450px;" /></p>';
// Look for the source string
preg_match( '/src=\".*?\"/', $html, $matches );
// If we found it, spit it out.
echo $matches ? $matches[0] : "No source";
Upvotes: 1
Reputation:
if alt=""
is empty by default and style is width: 2450px; height: 1054px;
by default you could use:
<?php
$str = '<p><img alt="" src="images/1.jpg" style="width: 2450px; height: 1054px;" /></p>';
$str = str_replace('<p><img alt="" src="','', $str);
$str = str_replace('" style="width: 2450px; height: 1054px;" /></p>','',$str);
echo $str; //Outputs: images/1.jpg
?>
Upvotes: 0