使用“preg_replace”删除字符串

时间:2017-12-07 05:02:16

标签: php preg-replace

我想使用“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>' );

我想从<style type=text/css>' )删除标签,直至( '</style>' );

我的代码是这样的:

$result3 = preg_replace("(\<style(.+?)<\/style>/", '', $result2);

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

感谢您的帮助。如果你能解释一下我的回答,我将不胜感激。

1 个答案:

答案 0 :(得分:-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