为了账号安全,请及时绑定邮箱和手机立即绑定

在 PHP中使用正则表达式查找 <head> 内的所有 <style> 标签

在 PHP中使用正则表达式查找 <head> 内的所有 <style> 标签

PHP
万千封印 2023-05-12 15:10:31
我正在尝试使用 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

        )


)


查看完整回答
反对 回复 2023-05-12
  • 1 回答
  • 0 关注
  • 136 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信