亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 202 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號