doudongfu8006 2017-03-01 06:20
浏览 53
已采纳

PHP正则表达式来准确获取我想要的字符串

I have a code for embedding a link for iframe.

$post_contetn =  explode('htt',$content);
$content_with_link = $post_contetn[0]; 
$link = 'htt'.$post_contetn[1]; 

But the problem is that, if I write

http://www.espn.com  was great

then it links "was great" is part of the $link.

How can I change (perhaps use regex) to only include the actual url?

======

If I incorporate siam's answer, should it be

            $regex = '/https?:\/\/.*?(?=\s)/';
            $post_contetn = preg_match($regex, $content, $linkarray);
            $content_with_link = $post_contetn[0]; 
            $link = $linkarray[0]
            echo $content_with_link;

I then edited to

            preg_match($regex, $content, $post_contetn);
            $content_with_link = $post_contetn[0]; 
            $link = $post_contetn[0]
            echo $content_with_link;

But the error still occurs at echo line.

  • 写回答

1条回答 默认 最新

  • dqteh7347 2017-03-01 06:29
    关注

    Try using the following regex :

    (?:https?:\/\/\S+)?\S+\.\S+\.?\S+
    

    see demo / explanation

    PHP

    <?php
       $content = 'http://www.espn.com  was great';
       $regex = '/(?:https?:\/\/\S+)?\S+\.\S+\.?\S+/';
       preg_match($regex, $content, $post_contetn);
       $link = $post_contetn[0];
       echo $link;
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站