2016-02-11 74 views
-1

我有这样的功能:正则表达式匹配跨度或?

function getTextBetweenTags($string, $tagname) { 
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/"; 
    preg_match($pattern, $string, $matches); 
    if(count($matches) > 0){ 
     return $matches[1]; 
    } 
} 

传递例如span作为参数$tagname让我来匹配任何span标签。我期望通过a|span将允许我发动任何aspan标签。但它不匹配任何东西。为什么?

+1

建议:使用['的XPath/DOM'(HTTP:/ /php.net/manual/en/class.domxpath.php) –

+0

可能在preg_match之前preg_引用您的模式 – SomeDude

+0

什么是失败的源代码示例?而不是'if(count($ matches)> 0){'只是'如果'preg_match'。 – chris85

回答

0

与分组尝试在括号(正如我们在评论说话):

function getTextBetweenTags($string, $tagname) { 
    $pattern = "/<($tagname)?.*>(.*)<\/($tagname)>/"; 
    preg_match($pattern, $string, $matches); 
    if(count($matches) > 0){ 
     return $matches[1]; 
    } 
} 

如果你通过$string = "a|span"你会获得$pattern = "/<(a|span)>";

+0

这将不匹配 Henrik Henriksson with pattern patter a | span? – Himmators

+0

它与您写的相同('?。*')。与你的代码唯一的不同是括号'[]'将一组被允许的字符串分组,'|' –

+2

'[]'是一个字符类,它允许单个字符,而不是组。这将允许's','p','a','n','|'和'a'。 – chris85