我正在尝试获取 href
的值第一个的属性 <a>
帖子中的标签是图片。
这是我到目前为止所拥有的:
$pattern = "/<a.+href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\").*>/i";
$output = preg_match_all($pattern, $post->post_content, $matches);
$first_link = $matches[1][0];
但是,这不起作用。
我有一个代码可以获取 src
<img>
的值确实有效的标签:
$pattern = "/<img.+src=[\'"]([^\'"]+)[\'"].*>/i";
$output = preg_match_all($pattern, $post->post_content, $matches);
$first_img = $matches[1][0];
因为我不是正则表达式和 php 方面的专家,所以我不知道我做错了什么。
我也找不到任何像样的、有条理的正则表达式指南,所以一个链接也很有用!
最佳答案
这不是您应该使用正则表达式解决的问题。如果你想解析 HTML,你需要的是一个 HTML 解析器,而 PHP 已经有一个非常适合你的解析器!
$html = <<<HTML
<a href="http://somesillyexample.com/some/silly/path/to/a/file.jpeg">
HTML;
$dom = new DomDocument;
$dom->loadHTML($html); // load HTML from a string
$elements = $dom->getElementsByTagName('a'); // get all elements with an 'a' tag in the DOM
foreach ($elements as $node) {
/* If the element has an href attribute let's get it */
if ($node->hasAttribute('href')) {
echo $node->getAttribute('href') . "\n";
}
}
/*
will output:
http://somesillyexample.com/some/silly/path/to/a/file.jpeg
*/
参见 DOMDocument文档以获取更多详细信息。
关于php - 正则表达式 + preg_match_all - 获取属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13779605/