我正在尝试使用 Regex 查找<style内部的所有标签<head>。我已经编写了在整个 HTML 中找到它的代码:$regex = '/(<style.*>(.*)<\/style>)/Usmi';preg_match_all($regex, $content, $matches);foreach ($matches[1] as $key => $style_tag) { $css = $matches[2][$key]; // $style_tag will contain full tag and $css will contain its content}但我只想<style>在里面找到标签<head>。我尝试了以下方法,但它只捕获了第一个<style>标签:$regex = '/(<style.*>(.*)<\/style>).*<\/head>/Usmi';preg_match_all($regex, $content, $matches);foreach ($matches[1] as $key => $style_tag) {}
1 回答
繁花不似锦
TA贡献1851条经验 获得超4个赞
使用 positive look ahead 检查是否有结束head标签
$content = "<html>
<head>
<style>something</style>
<style class='my-class'>other</style>
</head>
<body>
<style>content</style>
</body>
</html>";
preg_match_all('#(<style.*>(.*)</style>)(?=.*</head>)#Usmi', $content, $matches);
print_r($matches);
给我
Array
(
[0] => Array
(
[0] => <style>something</style>
[1] => <style class='my-class'>other</style>
)
[1] => Array
(
[0] => <style>something</style>
[1] => <style class='my-class'>other</style>
)
[2] => Array
(
[0] => something
[1] => other
)
)
- 1 回答
- 0 关注
- 169 浏览
添加回答
举报
0/150
提交
取消