结合两个regex函数剥离html标记


Combining two regex functions to strip html tags

我试图在html页面中获得H1文本,我使用了一个正则表达式,直到我们开始在一些页面上使用微格式来简化,我使用了页面的标题(H1标签作为"正在审查的项目")。

问题是我之前使用的正则表达式停止工作,所以我写了另一个正则表达式来执行,以防第一个返回空结果。我知道这很尴尬!!如何将以下内容组合成一个简单的正则表达式?:

//Get the H1 title
function get_tag( $attr, $value, $xml )
{
   $attr = preg_quote($attr);
   $value = preg_quote($value);
   $tag_regex2 = '/<h1>(.*?)<''/h1>/si';
   $tag_regex = '/<h1><span itemprop="itemreviewed">(.*?)<''/span><''/h1>/si';

   preg_match($tag_regex,
   $xml,
   $matches);
   if ($matches[1] == ""){
   preg_match($tag_regex2,
   $xml,
   $matches);
   };

   return $matches[1];
}

如果您愿意为了方便而牺牲健壮性(如果您使用正则表达式来解析HTML,您必须这样做:)),您可以使用

$tag_regex = '#<h1>(?:<span itemprop="itemreviewed">)?(.*?)(?:</span>)?</h1>#si';

/<h1>(?:<[^>]+>)?(.*?)(?:<[^>]+>)?<'/h1>/si通常用于删除<h1/>中的标记,但您可能需要对其进行一些自定义。如果你想删除上面列出的span,它看起来就像/<h1>(?:<span's+itemprop=["']itemreviewed["'][^>]*>)?(.*?)(?:<[^>]+>)?<'/h1>/si