2014-11-21 83 views
0

我想第一個src屬性,我用這正則表達式,但它刮所有src屬性:讓正則表達式匹配只有一次

(?<=src=").*?(?=") 

例子:

<img src="http://ia.media-imdb.com/images/M/[email protected]@._V1_SY317_CR0,0,214,317_AL_.jpg" /> 
<img src="http://ia.media-imdb.com/images/M/[email protected]_V1_SX86_CR0,0,86,86_AL_.jpg" /> 
<img src="http://ia.media-imdb.com/images/M/[email protected]_V1_SY86_CR33,0,86,86_AL_.jpg" /> 
<img src="http://ia.media-imdb.com/images/M/MV5BMTAxNTAwMTg0ODReQTJeQWpwZ15BbWU4MDMzNDE2NDMx._V1_SY86_CR33,0,86,86_AL_.jpg" /> 
+0

什麼是你期望的輸出?你正在運行哪種語言? – 2014-11-21 09:09:18

+0

@AvinashRaj:first src attribute =>'http://ia.media-imdb.com/images/M/MV5BMTY3NjY0MTQ0Nl5BMl5BanBnXkFtZTcwMzQ2MTc0Mw @@ ._ V1_SY317_CR0,0,214,317_AL_.jpg' – 2014-11-21 09:10:01

回答

1

你可以得到兩種方式第一img src屬性的值。

  1. 通過capturing group

    (?s)^(?:(?!<img\b[^<>]*?\bsrc=).)*<img\b[^<>]*?\bsrc="([^"]*)" 
    

抓鬥img src屬性的從組索引值1

DEMO

  • 通過\Kpositive lookahead assertion

    (?s)^(?:(?!<img\b[^<>]*?\bsrc=).)*<img\b[^<>]*?\bsrc="\K[^"]*(?=") 
    
  • 抓鬥img src屬性的從組索引值0

    DEMO

    +0

    @ nu11p我不是downvoter,但在PHP中,全局標誌是默認啓用的。 – 2014-11-21 09:21:28

    +0

    那麼我的錯誤。我已經刪除了答案。感謝兄弟的信息:) @Avinash拉傑 – nu11p01n73R 2014-11-21 09:26:26

    0

    嘗試:

    $re = "/src=[\"'](?<src>[^<>\"']+)['\"]/"; 
        $str = "<img src=\"http://ia.media-imdb.com/images/M/[email protected]@._V1_SY317_CR0,0,214,317_AL_.jpg\" />\n<img src=\"http://ia.media-imdb.com/images/M/[email protected]_V1_SX86_CR0,0,86,86_AL_.jpg\" />\n<img src=\"http://ia.media-imdb.com/images/M/[email protected]_V1_SY86_CR33,0,86,86_AL_.jpg\" />\n<img src=\"http://ia.media-imdb.com/images/M/MV5BMTAxNTAwMTg0ODReQTJeQWpwZ15BbWU4MDMzNDE2NDMx._V1_SY86_CR33,0,86,86_AL_.jpg\" />"; 
    
        preg_match($re, $str, $matches); 
        var_dump($matches['src']); 
    

    輸出:

    string 'http://ia.media-imdb.com/images/M/[email protected]@._V1_SY317_CR0,0,214,317_AL_.jpg' (length=114) 
    

    live demo