PHP - 解析字符串中 <img> 标签的 src 属性
PHP - parsing src attribute of <img> tag in string
在不使用任何外部库的情况下,解析在任意文本字符串中找到的第一个 <img>
标记的 src
属性的最简单但可靠的方法是什么?这意味着获取 <img>
标签的 src
属性的开始和结束 "
字符之间的所有内容。
我做了这个脚本,但在某些情况下它不是一个可靠的解决方案:
$string = $item['description'];
$arr = explode('img', $string);
$arr = explode('src', $arr[1]);
$arr = explode('=', $arr[1]);
$arr = explode('>', $arr[1]);
$pos1 = strpos($arr[0], '"')+1;
$pos2 = strrpos($arr[0], '"')-1;
if (!$pos1) {
$pos1 = strpos($arr[0], "'")+1;
$pos2 = strrpos($arr[0], "'")-1;
}
if ($pos1 && $pos2) {
$result = substr($arr[0], $pos1, $pos2);
}
else { $result = null; }
如果你想获取img标签所有属性的值,你需要做2个正则表达式。
1.获取img标签内容:
/<\s*img([^<>]+)>/
然后在捕获的内容上使用此正则表达式和函数 preg_match_all()
/\S+\s*=\s*[\'\"]([^\"\']+)[\'\"]/g
这是您的答案:
首先,你需要调用这个正则表达式,
<img(.*?)>
然后,为了得到其他属性,您需要对之前的结果进行另一个正则表达式调用
"(.*?)"
试试这个,
<img\s+src\s?\=\s?\"(https?\:\/\/[\w\.\/]+)\".*\/>
唯一最安全的方法是使用 DOMDocument
内置(在 PHP 5 中)class。使用getElementsByTagName()
,检查长度是否大于0,用getAttribute('src')
抓取第一项src
值:
$html = "YOUR_HTML_STRING";
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$imgs = $dom->getElementsByTagName('img');
if ($imgs->length > 0) {
echo $imgs->item(0)->getAttribute('src');
}
在不使用任何外部库的情况下,解析在任意文本字符串中找到的第一个 <img>
标记的 src
属性的最简单但可靠的方法是什么?这意味着获取 <img>
标签的 src
属性的开始和结束 "
字符之间的所有内容。
我做了这个脚本,但在某些情况下它不是一个可靠的解决方案:
$string = $item['description'];
$arr = explode('img', $string);
$arr = explode('src', $arr[1]);
$arr = explode('=', $arr[1]);
$arr = explode('>', $arr[1]);
$pos1 = strpos($arr[0], '"')+1;
$pos2 = strrpos($arr[0], '"')-1;
if (!$pos1) {
$pos1 = strpos($arr[0], "'")+1;
$pos2 = strrpos($arr[0], "'")-1;
}
if ($pos1 && $pos2) {
$result = substr($arr[0], $pos1, $pos2);
}
else { $result = null; }
如果你想获取img标签所有属性的值,你需要做2个正则表达式。
1.获取img标签内容:
/<\s*img([^<>]+)>/
然后在捕获的内容上使用此正则表达式和函数 preg_match_all()
/\S+\s*=\s*[\'\"]([^\"\']+)[\'\"]/g
这是您的答案: 首先,你需要调用这个正则表达式,
<img(.*?)>
然后,为了得到其他属性,您需要对之前的结果进行另一个正则表达式调用
"(.*?)"
试试这个,
<img\s+src\s?\=\s?\"(https?\:\/\/[\w\.\/]+)\".*\/>
唯一最安全的方法是使用 DOMDocument
内置(在 PHP 5 中)class。使用getElementsByTagName()
,检查长度是否大于0,用getAttribute('src')
抓取第一项src
值:
$html = "YOUR_HTML_STRING";
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$imgs = $dom->getElementsByTagName('img');
if ($imgs->length > 0) {
echo $imgs->item(0)->getAttribute('src');
}