【问题标题】:Regex: Extract Tweet Username and ID From URL正则表达式:从 URL 中提取推文用户名和 ID
【发布时间】:2017-01-01 00:49:49
【问题描述】:

我正在尝试在带有此正则表达式 #^https?://twitter\.com/(?:\#!/)?(\w+)/status(es)?/(\d+)$#is 的消息中获取推文 URL(如果找到)

但我的正则表达式似乎不正确,无法获取推文 URL。以下是我的完整代码

function gettweet($string)
{
    $regex = '#^https?://twitter\.com/(?:\#!/)?(\w+)/status(es)?/(\d+)$#is';
    $string = preg_replace_callback($regex, function($matches) {
        $user = $matches[2];
        $statusid = $matches[3];
        $url = "https://twitter.com/$user/status/$statusid";
        $urlen = urlencode($url);
        $getcon = file_get_contents("https://publish.twitter.com/oembed?url=$urlen");
        $con = json_decode($getcon, true);
        $tweet_html = $con["html"];
        return $tweet_html;
    }, $string);
    return $string;
}

$message="This is absolutely trending can you also see it here https://twitter.com/itslifeme/status/765268556133064704 i like it";
$mes=gettweet($message);
echo $mes;

【问题讨论】:

    标签: php json regex tweets


    【解决方案1】:

    这不能按预期工作的原因是因为您在正则表达式中包含了anchors,这表示模式必须从头到尾匹配。

    通过移除锚点,它匹配...

    $regex  = '#https?://twitter\.com/(?:\#!/)?(\w+)/status(es)?/(\d+)#is';
    $string = "This is absolutely trending can you also see it here https://twitter.com/itslifeme/status/765268556133064704 i like it";
    
    if (preg_match($regex, $string, $match)) {
        var_dump($match);
    }
    

    上面的代码给了我们...

    数组(4){ [0]=> 字符串(55)“https://twitter.com/itslifeme/status/765268556133064704” [1]=> 字符串(9)“它的生命” [2]=> 字符串(0)“” [3]=> 字符串(18)“765268556133064704” }

    另外,真的没有理由在你的表达式中包含dot all pattern modifier

    s (PCRE_DOTALL)

    如果设置了此修饰符,则模式中的点元字符匹配所有字符,包括换行符。没有它,换行符被排除在外。这个修饰符等价于 Perl 的 /s 修饰符。诸如 [^a] 之类的否定类始终匹配换行符,与此修饰符的设置无关。

    【讨论】:

    • 谢谢。正则表达式工作得很好,但是当我解析这个时,我没有从 json 得到任何响应。 $getcon = file_get_contents("publish.twitter.com/oembed?url=$urlen"); $con=json_decode($getcon, true); $getva=$con["url"];
    • 没有得到任何响应,或者json_decode返回null,according to the manual表示失败?还是只是file_get_contents本身返回了false,而according to the manual表示失败?您不会尝试在代码中进行任何类型的错误处理。当您认为代码每次都应该完美运行时,您的代码在这里可能会非常意外地失败,这并不罕见或意外。
    • 感谢谢里夫的回复。请是一个php新手。 json_decode 返回 null 但解析的推文 url 有效。请帮助我以最佳方式获得完美结果。我想从 json 数组中输出“html”并将其显示为我网站上的嵌入式推文。谢谢
    猜你喜欢
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多