2

I'm looking for a regex that will be able to replace all links like <a href="javascript://potentiallybadstuff"> Link </a> with a warning. I've been having a play but no success so far! I've always been bad with regex, can someone point me in the right direction? I have this so far:

Edit: People saying don't use Regex - the HTML will be the output of a markdown parser with all HTML tags in the markdown stripped. Therefore i know that the output of all links will be formatted as stated above, therefore regex would surely be a good tool in this particular situation. I am not allowing users to enter pure HTML. And SO has done something very similar, try creating a javascript link, and it will be removed

<?php
//Javascript link filter test
if(isset($_POST['jsfilter'])){
    $html = "<a href=\"". $_POST['jsfilter']."\"> JS Link </a>";
    $pattern = "/ href\\s*?=\\s*?[\"']\\s*?(javascript)\\s*?(:).*?([\"']) /is";
    $replacement = "\"javascript: alert('Javascript links have been blocked');\"";
    $html = preg_replace($pattern, $replacement, $html);
    echo $html;
}
?>
<form method="post">
<input type="text" name="jsfilter" />
<button type="submit">Submit</button>
</form>
4

4 回答 4

3

正确的正则表达式应该是:

$pattern = '/href="javascript:[^"]+"/';
$replacement = 'href="javascript:alert(\'Javascript links have been blocked\')"';
于 2013-06-20T13:14:50.747 回答
1

使用 strip_tags 和 htmlSpecialChars() 来显示用户生成的内容。如果要让用户使用特定的标签,请参考 BBcode。

于 2013-06-20T12:54:55.280 回答
0

试试这个代码。我想,这会有所帮助。

<?php
//Javascript link filter test
if(isset($_POST['jsfilter'])){
    $html = "<a href=\"". $_POST['jsfilter']."\"> JS Link </a>";
    $pattern = '/a href="javascript:(.*?)"/i';
    $replacement = 'a href="javascript: alert(\'Javascript links have been blocked\');"';
    $html = preg_replace($pattern, $replacement, $html);
    echo $html;
}
?>
于 2013-06-20T13:21:33.633 回答
0

您应该测试引号和双引号,处理空格等...

    $html = preg_replace( '/href\s*=\s*"javascript:[^"]+"/i' , 'href="#"' , $html );
    $html = preg_replace( '/href\s*=\s*\'javascript:[^i]+\'/i' , 'href=\'#\'' , $html );
于 2015-05-26T08:21:36.137 回答