问题
I have string with multiple image tags in it. Like this
<img src="/files/028ou2p5g/blogs/9d66329f4/5844644f69fe7-64.jpg">
I want to find FIRST such tag, and get image name from it 5844644f69fe7-64.jpg How can be this done in PHP asuming there is a lot of other text and tags in string ?
回答1:
You should use like what @moopet suggested. This is the code, but please give credit to @moopet.
$str = '<img src="/files/028ou2p5g/blogs/9d66329f4/5844644f69fe7-64.jpg">';
$doc = new DOMDocument();
$doc->loadHTML($str);
$first_img = $doc->getElementsByTagName("img")[0];
var_dump( basename($first_img->getAttribute('src')) );
回答2:
Don't use regex for this. Use PHP's DOM parser or an alternative to extract the tags, then use PHP's basename() function on the src
element to extract the filename.
回答3:
Use preg_match_all() to find all occurences and then get the first one.
Example:
<?php
preg_match_all('/<\s*img[^<>]+?src\s*=\s*[\'\"][^<>\'\"]+?\/([^<>\'\"\/]\.jpg)/', $html, $matches, PREG_SET_ORDER);
var_dump($matches[0]);
?>
来源:https://stackoverflow.com/questions/41036804/fnd-specific-place-in-string-and-get-data-from-it