How could this anti-xss regexp be bypassed: /<(?:\w+)\W+?[\w]/

I am working on it but I can't find a way.

Just to be sure that I have understood it correctly, this regexp search for a pattern with a '<', then one or more characters, then one or more non character and then a character.


EDIT: Here is the code:

$xss = $_POST['xss']; 

if (preg_match('/<(?:\w+)\W+?[\w]/', $xss)) {
     echo '<p>I don\'t think so</p>'; 
} else {
    echo $xss; 

1 Answer 1


It really depends on how you use this regex. I'll use PHP code as an example:

Unsafe Example: Replace

echo "replaced: " . preg_replace('/<(?:\w+)\W+?[\w]/', '', $_GET['input']);

This would not be safe. Example:


This is because your regex does what you think it does: it searches for < followed by one or more alphanumeric character, followed by one or more non-alphanumeric characters, and then a single alphanumeric character.

So in the above attack string, <a|a (another example for clarity: <aaa|||z) matches exactly this and will be removed. Thus, the remaining string is <script>....

Safer Example: Filter

If on the other hand you use it like this:

$isAttack = preg_match('/<(?:\w+)\W+?[\w]/', $_GET['input']);
if (!$isAttack) { echo "filtered: " . $_GET['input']; }

The above would not work.

Safer Example: Weaknesses

You should still be careful where you output user input, even if you use the regex like in the safer example. This for example would not be safe:

$isAttack = preg_match('/<(?:\w+)\W+?[\w]/', $_GET['input']);
if (!$isAttack) { echo "link: <a href="' . " . $_GET['input'] . '">click me</a>'; }

Example attack:

input=" onmouseover="alert('xss')

For more places where this kind of filtering is not good enough, see the owasp XSS Prevention Cheat Sheet.

  • See the Edit in my first post
    – ibrahim87
    Commented Oct 20, 2014 at 19:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .