0

i have a code like onclick=window.location='abc.html'> lala , i want to make a regular expression to cut this to meet the following requirments:

  1. if there is a > then the result should be > lala
  2. if there is not > then the string will cut till the space and the result will only be lala

i have done the following the preg_replace, but i am wrong, what is the problem?

$text=preg_replace('/(onclick)(.*?)(>|\s)/','',$text);
4

3 回答 3

0
<?php
echo preg_replace('/(onclick)(.*?)((?=>)|\s)/','',"onclick=window.location='abc.html'> lala");
echo preg_replace('/(onclick)(.*?)((?=>)|\s)/','',"onclick=window.location='abc.html' lala");
?>

您必须提前搜索 >,以免它被捕获和替换。(?=>)

于 2013-07-24T15:59:31.300 回答
0
$text = preg_replace('/onclick.+?((\s|>).+)/', "$1", $text);
于 2013-07-24T16:01:16.697 回答
0

一个干净的方法是使用 DOM,例如:

$doc = new DOMDocument();
@$doc->loadHtml($yourHtmlDocument);
$xpath = new DOMXPath($doc);
$tags = $xpath->query("//*[@onclick]");
foreach ($tags as $tag) {
    $tag->removeAttribute('onclick');
}
$result = $doc->saveHtml();
于 2013-07-24T16:10:48.380 回答