使用 preg_match_all() 努力匹配字符串

Struggling to match a string using preg_match_all()

我正在搜索这个:

<h1> sample string 123.456 - find me </h1>

请注意,我感兴趣的是 h1 标签之间的内容。也请不要说字符串是一个包含数字、字母and/or字符的任意组合的变量。因此,还需要使用相同的 preg_match_all 搜索在 h1 标签之间找到以下内容:

<h1>there are no numbers this time</h1>

<h1>this one may be tricky ?!-.</h1>

我现在尝试了以下方法:

preg_match_all("/<h1>[\w\d\D\s]+?<\/h1>$/siU", $input, $matches);
print_r($matches);

脚本运行...但是 $matches 数组在我 print_r() 时不包含任何值。因此它看起来像这样 'Array ( [0] => Array ( ) ) '

下面获取所有三个字符串:

<h1>\s?[a-z0-9\s?!.]*<\/h1> 

问题是,预期的结果是什么? 你可以试试这个:

$input = '<h1> Alphanumeric value here </h1>';
preg_match_all("/^<h1>(.*)<\/h1>/su", $input, $matches);
print_r($matches);

结果:

Array
(
    [0] => Array
        (
            [0] => <h1> Alphanumeric value here </h1>
        )

    [1] => Array
        (
            [0] =>  Alphanumeric value here 
        )

)
preg_match_all("%^<h1>[a-zA-Z0-9\s]*</h1>$%siU", $input, $matches);

这将在 <h1> 标签内 return 文本,因此如果您想要包含标签,只需执行

"<h1>".$result."</h1>"

使用解析器可能是您的最佳选择。您的 question/comments 不清楚并且与您试图识别的内容相矛盾。

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$html = '<h1>Hi</h1><h2>test</h2><strong>Test</strong><h1>More</h1>';
$doc->loadHTML($html);
libxml_use_internal_errors(false);
$h1s = $doc->getElementsByTagName('h1');
foreach ($h1s as $h1) {
    echo $h1->nodeValue . "\n";
}

然后您可以在 nodeValue 上使用正则表达式来确认值是否符合预期。

输出:

Hi
More

您最初问题的正则表达式可能是..

<h1>[a-zA-Z\d]+?<\/h1>

演示:https://regex101.com/r/lD5wQ3/1