2014-01-17 48 views
0

有人可以告訴我爲什麼這個正則表達式不能在PHP中工作,但模式在C#中工作?php正則表達式不工作,在C中工作#

我試圖複製一個工作功能,我在C#中,我試圖用我以前有相同的正則表達式,它不返回任何結果,我檢查了谷歌和理解PHP的正則表達式的用途一組不同的分隔符,但現在我不知道爲什麼它不起作用。

PHP:

$results_q = "#(?m)/watch-.*?title=#"; 
preg_match($results_q, $html, $results, PREG_PATTERN_ORDER);  

工作在C#:

var results = Regex.Matches(test, "(?m)/watch-.*?title="); 

我怎樣才能讓它在PHP的工作嗎?這種模式有什麼不同?

正則表達式主題:

<a href="/watch-2742524-Thor-The-Dark-World" title="Watch Thor The Dark World (2013)"> 

輸出應該是:/watch-2742524-Thor-The-Dark-World

這是我的PHP函數和它目前的工作,但只有一個返回結果,我想到了很多!因爲頁面上有幾個項目符合我的模式。

function parseURL($url, $page, $featured = false) { 

    $opts = array(
     'http'=>array(
       'method'=>"GET", 
       'header'=>"Accept-language: en\r\n" 
       ) 
      ); 

    $context = stream_context_create($opts); 

    $html = file_get_contents($url, false, $context); 
    $results_q = "/(?m)watch-.*?title=/"; 

    preg_match($results_q, $html, $results);  


    echo var_dump($results); 

} 
+4

請張貼您所期望的模式來匹配什麼,以及輸入你測試過的字符串不匹配。 –

+0

當然看到編輯,我測試過「#(?m)// watch - 。*?title =#」和「/(?m)/watch-.*?title=/」,沒有運氣。 – Dean

回答

2

您正在使用錯誤的標誌(的preg_match的最後一個參數),http://www.php.net/manual/ru/function.preg-match.php這裏你可以看到這一個PREG_OFFSET_CAPTURE是允許的。你可以省略這最後PARAM

preg_match($results_q, $html, $results); 

也是我修改一點點,你格局,rusult:

$html = "<a href=\"/watch-2742524-Thor-The-Dark-World\" title=\"Watch Thor The Dark World (2013)\">"; 
$html .= "<a href=\"/watch-asdf742524-Thor-The-Dark-World\" title=\"Watch Thor The Dark World (2013)\">"; 

$results_q = "#(?m)(/watch-[^\"]*).*?title=#i"; 
$res = preg_match_all($results_q, $html, $results); 
var_dump($results); 
+0

它現在正在工作,但只返回一個結果 – Dean

+0

如果您期望多個匹配,請使用['preg_match_all()'](http://us2.php.net/manual/en/function.preg-match-all.php)。 –

+0

謝謝你,工作! – Dean

0

這爲我工作。

保持簡單,在\ S *是有由於看不見的空白,可能是有,也試圖避免的情況下的靈敏度和東西...

$ results_q =「#href =」(/手錶。 *) 「\ S *標題#Uisx」;

preg_match($ results_q,$ html,$ results);

但只是一個quicky我的手機嘗試...

檢查這兩個網站

​​

php regex tester