【问题标题】:PHP- Preg_replace tag name and its contentsPHP- Preg_replace 标签名称及其内容
【发布时间】:2016-09-18 01:36:06
【问题描述】:

我有一个字符串 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;

但它显示相同的字符串而没有删除&lt;style&gt; 标记。 我也尝试通过做

来仅替换 &lt;style&gt; 标签
$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();

但在所有情况下,&lt;style&gt; 及其内容的输出都相同

【问题讨论】:

  • 在 preg_replace 之前制作 var_dump($description),因为你的代码似乎没问题;
  • var_dump() 相同,
  • 如果你从php显示的页面中获取你的字符串,你可能看不到你的字符串是&amp;lt;script&amp;gt;,因为它可能以这种形式保存在数据库中
  • 没错,怎么做?当我在同一个字符串上执行var_dump() 时,我看到string(8234) 但是当我将字符串粘贴到IDEone 上并执行var_dump() 时,我看到string(6413)
  • html_entity_decode()

标签: php css regex preg-replace str-replace


【解决方案1】:

您的正则表达式does work,但我可以建议simpler pattern,使用非贪婪量词:

<style>.*?<\/style>

【讨论】:

  • 我看到这个错误,你能写完整行吗?Unknown modifier .
  • 检查 IDEone 链接。一个是你的,一个是更简单的模式。
  • unknown 修饰符可能表示未转义的模式分隔符 (/) 应该是 (\/) ?见stackoverflow.com/a/5589826/244811
  • 它适用于 IDEone,但不适用于我的 string,我应该将完整的字符串粘贴到这里吗?
  • 用你输入的字符串修改IDEone,并给出链接。
猜你喜欢
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2018-10-28
  • 2010-12-03
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多