gpt4 book ai didi

php - 另一个小正则表达式问题

转载 作者:行者123 更新时间:2023-11-28 01:49:54 25 4
gpt4 key购买 nike

我知道不鼓励解析 HTML,但我知道事实上这是受控情况下的最佳选择。我的情况是,我需要一个正则表达式来查找 html 页面上的所有预格式化文本 ( <pre>) 语句。这似乎很容易简单地用谷歌搜索,但我没有找到任何结果。此外,<pre>语句需要包含一个字符串,在我的例子中是“gisformat”。换句话说,此正则表达式需要返回 HTML 文件中包含“gisformat”的所有预格式化文本语句。我知道它是这样的,但我不确定在中间放什么:/<pre>(what should I put here)</pre>/

编辑 1:我正在使用 PHP,是的,我看过这篇文章,包括答案 #2 RegEx match open tags except XHTML self-contained tags

最佳答案

正则表达式方式:

preg_match_all('~<pre\b[^>]*>(?>[^<g]+|g(?!isformat)|<(?!/pre))*gisformat(?>[^<]+|<(?!/pre>))*</pre>~', $subject, $matches);
print_r($matches[0]);

DOM 方式:

$doc = new DOMDocument();
@$doc->loadHTML($subject);
$preNodes = $doc->getElementsByTagName('pre');

foreach($preNodes as $preNode) {
if (strpos($preNode->nodeValue, 'gisformat') !== false)
$result[] = $preNode->ownerDocument->saveXML($preNode);
}
print_r($result);

图案细节:

 # the opening tag #
<pre\b [^>]* >

# content before the first "gisformat" #
(?>
[^<g]+ # all that is not a "<" or a "g"
| # OR
g(?!isformat) # a "g" not followed by "isformat"
| # OR
<(?!/pre) # a "<" not followed by "/pre"
)* # repeat the group zero or more times

# target #
gisformat

# content until the closing tag #
(?>[^<]+|<(?!/pre>))*

# closing tag #
</pre>

关于php - 另一个小正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20689085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com