使用preg_match排除标记内的标记

时间:2015-03-25 14:45:21

标签: php regex

我想在两个标签之间获取文本,但不包括内部的任何其他标签,例如:

$text = "<h3><p>I dont want this text</p>But I do want this!</h3><p>some other text that I dont want</p>";

我唯一需要的是<h3>But I do want this!</h3>,并且应该排除其中可能存在的所有其他标签。

这可以用preg_match / preg_replace吗?

目前我所拥有的一切:

if(preg_match("/<h3>(.*)<\/h3>/s", $text, $match)){
    $text = $match[0];
}

$text = preg_replace("#<\s*img[^>]*>#", "", $text);

1 个答案:

答案 0 :(得分:1)

这是你可以尝试的正则表达式:

(?:<(h\d)>[^<>]*?)(?:<(?!\2).*>)\K(.+?)<\/\1>

请参阅example

第2组拥有你需要的东西。

如果在开始标记后面有文字,您可能也会遇到这种情况。然后,我会使用this regex

(?:<(h\d)>([^<>]*?))(?:<(?!\2).*>)\K(.+?)<\/\1>

只需将第2组和第3组合并。

以下是适用于Tutorialspoint的示例代码:

<?php
    $re = "/(?:<(h\\d)>([^<>]*?))(?:<(?!\\2).*>)\\K(.+?)(?=<\\/\\1>)/"; 
    $str = "<h3>Maybe this, too. <p>I dont want this text</p><p>I dont want this text</p>But I do want this!</h3><p>some other text that I dont want</p>"; 
    preg_match_all($re, $str, $matches);
    $group2 = each($matches[2]);
    $group3 = each($matches[3]);
    print_r($group2["value"]);
    print_r($group3["value"]);
?>