php 使用 preg_match 在字符串中查找 img 标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8416045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using preg_match to find an img tag in a string
提问by Pseudorandom
How can I find an HTML tag in a string with PHP?
如何使用 PHP 在字符串中找到 HTML 标记?
This is a record in my database:
这是我数据库中的一条记录:
$str = "This is me <img src='images/mardagz.png' width='200' /> :) when i was 4th year highschool hahah so funny...";
I'm trying to get the contents of the <img>
tag. This is the code I am using:
我正在尝试获取<img>
标签的内容。这是我正在使用的代码:
$gimg = preg_match('/<img[^>]+\>/i', $str , $matches) ? $matches[1]: '<img src="http://facebook.com/username/profile.png" width="200" />
But, this code always gives me this error: Notice: Undefined offset: 1 in mardagz.blog\post.php on line 19
但是,这段代码总是给我这个错误: Notice: Undefined offset: 1 in mardagz.blog\post.php on line 19
What should I do?
我该怎么办?
回答by Ferdinand Beyer
$matches[1]
holds the text that matched the first groupin the search pattern, but your pattern does not have any groups. Groups are defined with parentheses.
$matches[1]
保存与搜索模式中的第一组匹配的文本,但您的模式没有任何组。组用括号定义。
Either put your whole pattern in a group like this:
要么将您的整个模式放在这样的组中:
preg_match('/(<img[^>]+>)/i', $str, $matches)
or just use $matches[0]
to get the whole text that matched.
或者只是$matches[0]
用来获取匹配的整个文本。
回答by Jake Lucas
You could get the img tag with regex but if I were you I wouldn't use regex for this.
您可以使用正则表达式获取 img 标签,但如果我是您,我不会为此使用正则表达式。
I think a better idea would be to use an HTML parser like this: http://simplehtmldom.sourceforge.net/
我认为更好的主意是使用这样的 HTML 解析器:http: //simplehtmldom.sourceforge.net/
Or you could use PHP's DOM Library: http://jp.php.net/dom
或者你可以使用 PHP 的 DOM 库:http: //jp.php.net/dom