【问题标题】:PHP regex to exactly obtain a string I wantPHP正则表达式来准确获取我想要的字符串
【发布时间】:2017-03-01 06:20:59
【问题描述】:

我有一个嵌入 iframe 链接的代码。

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

但问题是,如果我写了

http://www.espn.com  was great

然后它链接“很棒”是 $link 的一部分。

如何更改(可能使用正则表达式)以仅包含实际网址?

======

如果我把暹罗的回答结合起来,应该是

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

然后我编辑为

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

但错误仍然出现在回显线。

【问题讨论】:

    标签: php regex iframe


    【解决方案1】:

    尝试使用以下正则表达式

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

    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;
    ?>
    

    【讨论】:

    • @user42459 您不能将preg_match() 分配给变量。只需将$linkarray 替换为$post_contetn,您的$content 的格式是什么?
    • @user42459 那么也许你对其他东西有问题。代码工作得很好。见here
    • @user42459 是的,这很奇怪。 check now,我更新了答案。
    • @user42459 没关系,您可以随时提问。无论如何,我进一步更新了答案。现在它应该可以正常工作了。并且没有 php 对 regex 没有不同的规则。
    • @user42459 不,它不显示整个asdf espn.com,它只显示espn.comhere
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多