php
  • regex
  • html-parsing
  • preg-match
  • 2015-07-20 71 views 1 likes 
    1

    我有一個正則表達式:的preg_match不匹配的HTML標記子模式

    $reg = '/<a class="title".*>(.*)<\/a>/'; 
    

    及以下文字:

    $text = '<h3 class="carousel-post-title"><a class="title" href="/first-link/">Some text<br /><span class="title-highlight">with a span</span></a></h3>' 
    

    我傳遞到的preg_match:

    $matches = []; 
    preg_match($reg, $text, $matches); 
    

    這將返回

    Array (
        [0] => <a class="title" href="/first-link/">Some text<br /><span class="title-highlight">with a span</span></a> 
        [1] => 
    ) 
    

    $text2 = '<h3 class="carousel-post-title"><a class="title" href="/second-link/">Some text here</a></h3>'; 
    
    preg_match($reg, $text2, $matches); 
    

    回報

    Array 
    (
        [0] => <a class="title" href="/second-link/">Some text here</a> 
        [1] => Some text here 
    ) 
    

    這是爲什麼?爲什麼子模式「(。*)」與'span'不匹配?

    +2

    '。*'是貪婪的,它儘可能地吃(ᗧ•••)。使用'。*?' – Rizier123

    +0

    @ splash58這與非貪心,'。*?'基本相同。 –

    回答

    0

    所以你的模式更改爲

    $reg = '/<a class="title"[^>]*>([^<]*)<\/a>/'; 
    

    ,它知道你想要的任何東西,除非它是在第一部分<或在第二部分>

    <a class="title"[^>]*> //Get the opening tag 
    ([^<]*) //match anything until you reach a closing tag 
    <\/a> // your closing tag 
    
    相關問題