【问题标题】:Extract urls from a string [duplicate]从字符串中提取网址[重复]
【发布时间】:2016-10-10 20:59:19
【问题描述】:

我有这个字符串:

http://sh.st/st/8052f1bbc624add41cd2a6236f76cfc8/https://www.rapidvideo.com/embed/o1cTaZbux

我想从中提取 url。

我的代码:

$pattern = '@((https?://)?([-\\w]+\\.[-\\w\\.]+)+\\w(:\\d+)?(/([-\\w/_\\.]*(\\?\\S+)?)?)*)@';

$str= "http://sh.st/st/8052f1bbc624add41cd2a6236f76cfc8/https://www.rapidvideo.com/embed/o1cTaZbux";

if($num_found = preg_match_all($pattern, $str, $out))
{
  echo "FOUND ".$num_found." LINKS:\n";
  print_r($out[0]);
}

但是输出错误:

Array
(
    [0] => http://sh.st/st/8052f1bbc624add41cd2a6236f76cfc8/https
    [1] => www.rapidvideo.com/embed/o1cTaZbux
)

我要输出:

Array
(
    [0] => http://sh.st/st/8052f1bbc624add41cd2a6236f76cfc8
    [1] => https://www.rapidvideo.com/embed/o1cTaZbux
)

请帮忙

【问题讨论】:

  • 你可以在 http(s):// 上拆分就足够了。你真的不需要剩下的
  • 我不知道该怎么做。你能帮助我吗?谢谢!
  • 您发布了一个链接,指向 bones 剧集的非法副本。 -1
  • 你可能想要一个non-greedy search - 我试着测试一下,但regex101.com 不喜欢你现有的字符串。

标签: php


【解决方案1】:

也许对语句等不感兴趣,而是通过函数preg_split 来做?

例如。 $urls = preg_split('/ (http|https) /', $str, PREG_SPLIT_DELIM_CAPTURE);

编辑

为此,您必须添加新标志 + 相互添加结果。

$urls = preg_split('/(http|https)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

foreach ($urls as $k => $v) {
    if ($k % 2 != 0) {
        continue;
    }
    $list[] = $urls[$k].$urls[$k+1];
}

【讨论】:

  • 这是结果:[1] => ://sh.st/st/8052f1bbc624add41cd2a6236f76cfc8/ [2] => s://www.rapidvideo.com/embed/o1cTaZbux
  • 我想保留 http 和 https 到链接
  • 查看我的编辑,它包含正确的代码:)
【解决方案2】:

$str= "http://sh.st/st/8052f1bbc624add41cd2a6236f76cfc8/https://www.rapidvideo.com/embed/o1cTaZbux";


$foo = preg_split('#(http://)|(https://)#', $str,0,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);



for ($i = 0; $i < sizeof($foo); $i += 2) {
    $delim = isset($foo[$i + 1]) ? $foo[$i + 1] : '';
    $tmp[] = $foo[$i] . $delim;
}
print_r($tmp);

数组(
[0] => http://sh.st/st/8052f1bbc624add41cd2a6236f76cfc8/
[1] => https://www.rapidvideo.com/embed/o1cTaZbux
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2012-12-14
    • 2017-09-24
    • 2018-06-11
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多