正则表达式捕获不需要的左侧字符
Regex catch unwanted left side char
以下正则表达式捕获所有 HTML 样式标签:
[^noscript\>]<style[^>]*>([^<]+)?<[\s\/]+style>
第一部分[^noscript>]用于忽略任何由noscript标签包裹的样式标签。
问题是,模式似乎 return 不需要的左侧字符,如何避免?请参阅此示例 https://regex101.com/r/aA6ihs/1/
虽然使用 HTML 解析器会更好,但您可以使用 (*SKIP)(*FAIL)
跳过所有 <noscript>
标记 - 尝试匹配 <noscript>...</noscript>
,并且如果匹配,则在末尾使模式失败,并继续搜索匹配 after the end:
<noscript>.*?<\/noscript>(*SKIP)(*FAIL)|<style[^>]*>([^<]+)?<[\s\/]+style>
在这里,我们将简单地捕获 noscript
标签,添加一个 if
语句来忽略这些标签,然后我们将使用一个简单的表达式重新调整我们想要的输出,例如:
(<noscript>)[\s\S]+?<\/noscript>|<style(.+?)>(.+?)<\/style>
Demo
测试
$re = '/(<noscript>)[\s\S]+?<\/noscript>|<style(.+?)>(.+?)<\/style>/mi';
$str = '<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<style type="text/css"></style>
<noscript><style>
< / style></noscript>
<!-- Twitter Cards Meta by USM STARTS-->
<meta name="twitter:card" content="summary" />
<style type="text/css">.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style>
<link rel="pingback" href="/xmlrpc.php">
<noscript><style>
< / style></noscript>
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $key => $value) {
if ($value[1] != '<noscript>') {
echo $value[3];
}
}
输出
.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}
以下正则表达式捕获所有 HTML 样式标签:
[^noscript\>]<style[^>]*>([^<]+)?<[\s\/]+style>
第一部分[^noscript>]用于忽略任何由noscript标签包裹的样式标签。
问题是,模式似乎 return 不需要的左侧字符,如何避免?请参阅此示例 https://regex101.com/r/aA6ihs/1/
虽然使用 HTML 解析器会更好,但您可以使用 (*SKIP)(*FAIL)
跳过所有 <noscript>
标记 - 尝试匹配 <noscript>...</noscript>
,并且如果匹配,则在末尾使模式失败,并继续搜索匹配 after the end:
<noscript>.*?<\/noscript>(*SKIP)(*FAIL)|<style[^>]*>([^<]+)?<[\s\/]+style>
在这里,我们将简单地捕获 noscript
标签,添加一个 if
语句来忽略这些标签,然后我们将使用一个简单的表达式重新调整我们想要的输出,例如:
(<noscript>)[\s\S]+?<\/noscript>|<style(.+?)>(.+?)<\/style>
Demo
测试
$re = '/(<noscript>)[\s\S]+?<\/noscript>|<style(.+?)>(.+?)<\/style>/mi';
$str = '<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<style type="text/css"></style>
<noscript><style>
< / style></noscript>
<!-- Twitter Cards Meta by USM STARTS-->
<meta name="twitter:card" content="summary" />
<style type="text/css">.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style>
<link rel="pingback" href="/xmlrpc.php">
<noscript><style>
< / style></noscript>
';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
foreach ($matches as $key => $value) {
if ($value[1] != '<noscript>') {
echo $value[3];
}
}
输出
.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}