Fnd specific place in string and get data from it

别说谁变了你拦得住时间么 提交于 2019-12-16 18:03:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!