dongshi9526 2016-10-10 20:59
浏览 86

从字符串中提取网址[复制]

This question already has an answer here:

I have this string:

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

And I want to extract urls separate from this.

My code:

$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:
";
  print_r($out[0]);
}

But the output is wrong:

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

I want to output:

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

Please help

</div>
  • 写回答

2条回答 默认 最新

  • doufu7464 2016-10-10 21:07
    关注

    Maybe don't have fun with statements etc. and do it by function preg_split?

    Eg. $urls = preg_split('/ (http|https) /', $str, PREG_SPLIT_DELIM_CAPTURE);

    EDIT

    To do this you must add new flag + add results to each other.

    $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];
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程