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

我正在尝试使用 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) {


}


万千封印
浏览 170回答 1
1回答

繁花不似锦

使用 positive look ahead 检查是否有结束head标签$content = "<html><head>&nbsp; <style>something</style>&nbsp; <style class='my-class'>other</style></head><body>&nbsp; <style>content</style></body></html>";preg_match_all('#(<style.*>(.*)</style>)(?=.*</head>)#Usmi', $content, $matches);print_r($matches);给我Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => <style>something</style>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => <style class='my-class'>other</style>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => <style>something</style>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => <style class='my-class'>other</style>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [2] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => something&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => other&nbsp; &nbsp; &nbsp; &nbsp; ))
打开App,查看更多内容
随时随地看视频慕课网APP