PHP- Preg_replace 标签名称及其内容
PHP- Preg_replace tag name and its contents
我有一个像这样的字符串
string(8234) "<style>.{ margin-bottom:10px; float:left; display: inline-block; width:56%; text-align:left; padding-right:20px; padding-left:20px; } . > p { display: table-cell; height: 150px; vertical-align: middle; }..................</style>.................
我想删除 <style>
标签及其所有内容。
我试过了
$description = $product_info['description']; // the string with style tag
$text = preg_replace('/<\s*style.+?<\s*\/\s*style.*?>/si', ' ', $description );
echo $text;
但它显示相同的字符串而不删除 <style>
标记。
我还尝试通过
仅替换 <style>
标签
$text = str_replace("<style>", "", $description);
但这也根本不起作用。我一次又一次地看到相同的字符串。我也尝试过 DOMParser
$doc = new DOMDocument();
$doc->loadHTML($description);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//style') as $node) {
$node->parentNode->removeChild($node);
}
$text = $doc->saveHTML();
但在所有情况下,输出与 <style>
及其内容相同
您的正则表达式 does work, but might I suggest a simpler pattern,使用非贪婪量词:
<style>.*?<\/style>
我有一个像这样的字符串
string(8234) "<style>.{ margin-bottom:10px; float:left; display: inline-block; width:56%; text-align:left; padding-right:20px; padding-left:20px; } . > p { display: table-cell; height: 150px; vertical-align: middle; }..................</style>.................
我想删除 <style>
标签及其所有内容。
我试过了
$description = $product_info['description']; // the string with style tag
$text = preg_replace('/<\s*style.+?<\s*\/\s*style.*?>/si', ' ', $description );
echo $text;
但它显示相同的字符串而不删除 <style>
标记。
我还尝试通过
<style>
标签
$text = str_replace("<style>", "", $description);
但这也根本不起作用。我一次又一次地看到相同的字符串。我也尝试过 DOMParser
$doc = new DOMDocument();
$doc->loadHTML($description);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//style') as $node) {
$node->parentNode->removeChild($node);
}
$text = $doc->saveHTML();
但在所有情况下,输出与 <style>
及其内容相同
您的正则表达式 does work, but might I suggest a simpler pattern,使用非贪婪量词:
<style>.*?<\/style>