问题描述
$img = '<img src="http://some-img-link" alt="some-img-alt"/>';
$src = preg_match('/<img src=\"(.*?)\">/', $img);
echo $src;
我想从img标签中获取 src
值,也许还有alt值
I want to get the src
value from the img tag and maybe the alt value
推荐答案
假定您总是得到问题中所示的img html.
Assuming you are always getting the img html as you shown in the question.
现在,您在正则表达式中提供了这样的说法:在src属性之后,它给定了img的结束标记.但是在字符串中也有一个alt属性.因此,您也需要关心它.
Now in the regular expression you provided its saying that, after the src attribute its given the closing tag for img. But in the string there is an alt attribute also. So you need to care about it also.
/<img src=\"(.*?)\".*\/>/
如果要同时检查alt,则检查正则表达式.
And if you are going to check alt also then the regular expression.
/<img src=\"(.*?)\"\s*alt=\"(.*?)\"\/>/
您还只是在检查其是否匹配.如果需要获取匹配项,则需要在preg_match中提供第三个参数,以填充匹配项.
Also you are just checking whether its matched or not. If you need to get the matches, you need to provide a third parameter to preg_match which will fill with the matches.
$img = '<img src="http://some-img-link" alt="some-img-alt"/>';
$src = preg_match('/<img src=\"(.*?)\"\s*alt=\"(.*?)\"\/>/', $img, $results);
var_dump($results);
注意:上面给出的正则表达式不是那么通用,如果您可以提供将出现的img字符串,则将提供更强大的正则表达式.
Note : The regex given above is not so generic one, if you could provide the img strings which will occur, will provide more strong regex.
这篇关于如何从img标签获取链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!