2016-08-24 32 views
1

我试图获取鸣叫URL,如果发现,在消息与此正则表达式#^https?://twitter\.com/(?:\#!/)?(\w+)/status(es)?/(\d+)$#is正则表达式:提取资料Tweet的用户名和ID从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; 

回答

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); 
} 

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

 
array(4) { 
    [0]=> 
    string(55) "https://twitter.com/itslifeme/status/765268556133064704" 
    [1]=> 
    string(9) "itslifeme" 
    [2]=> 
    string(0) "" 
    [3]=> 
    string(18) "765268556133064704" 
} 

此外,还有实在没有理由在您表达dot all pattern modifier

S(PCRE_DOTALL

如果设定了此修正,在模式中的圆点元字符的所有字符,包括换行匹配。没有它,换行符被排除在外。这个修饰符相当于Perl的/ s修饰符。否定类如[^ a]总是匹配换行符,与此修饰符的设置无关。

+0

谢谢。正则表达式工作完美,但是当我在这里解析,我没有得到任何JSON响应。 $ getcon = file_get_contents(“https://publish.twitter.com/oembed?url=$urlen”); $ con = json_decode($ getcon,true); $ getva = $ con [“url”]; –

+0

没有得到任何回应,或'json_decode'返回null,[根据手册](http://php.net/json-decode)表示失败?还是只是'file_get_contents'本身返回'false',[根据手册](http://php.net/file-get-contents)表示失败?你不会试图在你的代码中进行任何类型的错误处理。当你相信它每次都能完美工作时,你的代码在这里出乎意料地失败并不罕见或意外。 – Sherif

+0

感谢您的回复谢里夫。请为php新手。 json_decode返回null,但解析的tweet url是有效的。请帮助我以获得完美结果的最佳方式。我想从json数组输出'html',并在我的网站上显示为嵌入式推文。谢谢 –