gpt4 book ai didi

php - 在包含 HTML 代码的字符串中抓取 URL

转载 作者:可可西里 更新时间:2023-11-01 00:41:42 25 4
gpt4 key购买 nike

我有一个字符串,例如:

$html = '<p>hello<a href="https://www.youtube.com/watch?v=7HknMcG2qYo">world</a></p><p>hello<a href="https://youtube.com/watch?v=37373o">world</a></p>';

我想在字符串中搜索以 youtube.comyoutu.be 开头的 first URL 并将其存储在变量中$first_found_youtube_url

我怎样才能有效地做到这一点?

我可以执行 preg_matchstrpos 来查找 url,但不确定哪种方法更合适。

最佳答案

我不久前写了这个函数,它使用正则表达式并返回一组唯一的 url。既然你想要第一个,你可以只使用数组中的第一个项目。

function getUrlsFromString($string) {
$regex = '#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#i';
preg_match_all($regex, $string, $matches);
$matches = array_unique($matches[0]);
usort($matches, function($a, $b) {
return strlen($b) - strlen($a);
});
return $matches;
}

示例:

$html = '<p>hello<a href="https://www.youtube.com/watch?v=7HknMcG2qYo">world</a></p><p>hello<a href="https://youtube.com/watch?v=37373o">world</a></p>';
$urls = getUrlsFromString($html);
$first_found_youtube = $urls[0];

使用 YouTube 特定的正则表达式:

function getYoutubeUrlsFromString($string) {
$regex = '#(https?:\/\/(?:www\.)?(?:youtube.com\/watch\?v=|youtu.be\/)([a-zA-Z0-9]*))#i';
preg_match_all($regex, $string, $matches);
$matches = array_unique($matches[0]);
usort($matches, function($a, $b) {
return strlen($b) - strlen($a);
});
return $matches;
}

例子:

$html = '<p>hello<a href="https://www.youtube.com/watch?v=7HknMcG2qYo">world</a></p><p>hello<a href="https://youtube.com/watch?v=37373o">world</a></p>';
$urls = getYoutubeUrlsFromString($html);
$first_found_youtube = $urls[0];

关于php - 在包含 HTML 代码的字符串中抓取 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34445347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com