【问题标题】:Removing string using "preg_replace" [duplicate]使用“preg_replace”删除字符串 [重复]
【发布时间】:2017-12-07 05:02:15
【问题描述】:

我想使用“preg_replace”删除一些 html/js 标记。这是我的html标签:

<style type=text/css>' );document.write( '@media Print' );document.write( '{' );document.write( 'BODY {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TABLE {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TR {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TD {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( '}' );document.write( '</style>' );

我想从&lt;style type=text/css&gt;' )( '&lt;/style&gt;' ); 中删除标签。

我的代码是这样的:

$result3 = preg_replace("(\&lt;style(.+?)&lt;\/style&gt;/", '', $result2);

但是当我运行它时没有任何东西被删除。

感谢您的帮助。另外,如果您能向我解释答案,我将不胜感激。

【问题讨论】:

  • $result3 = preg_replace("/&lt;style type=text/css&gt;/", "'&lt;/style&gt;'", $result2);
  • 你也可以使用 substr 和 strpos 来做到这一点。
  • 你确定不应该是 $result3 = preg_replace("(
  • 没人工作。
  • @AlivetoDie--Anantsingh 我想删除所有这些 html 标记,而不是将其替换为 &lt;/style&gt;&lt;/style&gt;我也想删除。

标签: php preg-replace


【解决方案1】:

你需要像下面这样使用preg_replace(离线测试):

<?php
$string = "another text above here";
$string .= "<style type=text/css>' );document.write( '@media Print' );document.write( '{' );document.write( 'BODY {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TABLE {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TR {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( 'TD {' );document.write( 'DISPLAY: none; print: none' );document.write( '}' );document.write( '}' );document.write( '</style>' );";

$string = preg_replace("/<!--.*?-->/", "", $string);
$string = preg_replace("/\([^)]+\)/","",$string);

echo $string;
?>

// Below Output will come
another text above here

【讨论】:

  • 反对者请在评论中解释。
  • @ainodoramaaa2 你试过我的解决方案了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多