2016-08-24 35 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',並在我的網站上顯示爲嵌入式推文。謝謝 –