可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I would like to get the SRC attribute into a variable in this example:

So for example - I would like to get a variable $foo = "/images/image.jpg"
. Important! The src attribute will be dynamic, so it mustn't be hardcoded. Is there any quick and easy way to do this?
Thanks!
EDIT: The image will be a part of a huge string that is basically the content of a news story. So the image is just a part of that.
EDIT2: There will be more images in this string, and I would only want to get the src of the first one. Is this possible?
回答1:
Use a HTML parser like DOMDocument
and then evaluate the value you're looking for with DOMXpath
:
$html = '
'; $doc = new DOMDocument(); $doc->loadHTML($html); $xpath = new DOMXPath($doc); $src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"
Or for those who really need to save space:
$xpath = new DOMXPath(@DOMDocument::loadHTML($html)); $src = $xpath->evaluate("string(//img/@src)");
And for the one-liners out there:
$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));
回答2:
You would be better off using a DOM parser for this kind of HTML parsing. Consider this code:
$html = '
'; $doc = new DOMDocument(); libxml_use_internal_errors(true); $doc->loadHTML($html); // loads your html $xpath = new DOMXPath($doc); $nodelist = $xpath->query("//img"); // find your image $node = $nodelist->item(0); // gets the 1st image $value = $node->attributes->getNamedItem('src')->nodeValue; echo "src=$value\n"; // prints src of image
OUTPUT:
src=/images/image.jpg
回答3:
I have done that the more simple way, not as clean as it should be but it was a quick hack
$htmlContent = file_get_contents('pageURL'); // read all image tags into an array preg_match_all('/
]+>/i',$htmlContent, $imgTags); for ($i = 0; $i
回答4:
I know people say you shouldn't use regular expressions to parse HTML, but in this case I find it perfectly fine.
$string = '
'; preg_match('/
回答5:
$imgTag =
LOB; preg_match('%%i', $imgTag, $matches); $imgSrc = $matches[1];
DEMO
NOTE: You should use an HTML Parser like DOMDocument
and NOT a regex.
回答6:
$str = '
'; preg_match('/(src=["\'](.*?)["\'])/', $str, $match); //find src="X" or src='X' $split = preg_split('/["\']/', $match[0]); // split by quotes $src = $split[1]; // X between quotes echo $src;
Other regexp's can be used to determine if the pulled src tag is a picture like so:
if(preg_match('/([jpg]{3}$)|([gif]{3}$)|([jpeg]{3}$)|([bmp]{3}$)|([png]{3}$)/', $src) == 1) { //its an image }
回答7:
There could be two easy solutions:
- HTML it self is an xml so you can use any XML parsing method if u load the tag as XML and get its attribute tottally dynamically even dom data attribute (like data-time or anything).....
- Use any html parser for php like http://mbe.ro/2009/06/21/php-html-to-array-working-one/ or php parse html to array Google this