Alex Rivera | Logout

A regular expression to exclude a word/string

Asked 2010-01-16T21:07:44.853
492

I have a regular expression as follows:

^/[a-z0-9]+$

This matches strings such as /hello or /hello123.

However, I would like it to exclude a couple of string values such as /ignoreme and /ignoreme2.

I've tried a few variants but can't seem to get any to work!

My latest feeble attempt was

^/(((?!ignoreme)|(?!ignoreme2))[a-z0-9])+$
Edit
Report

1 Answer

62

This should do it:

^/\b([a-z0-9]+)\b(?<!ignoreme|ignoreme2|ignoreme3)

You can add as many ignored words as you like. Here is a simple PHP implementation:

$ignoredWords = array('ignoreme', 'ignoreme2', 'ignoreme...');

preg_match('~^/\b([a-z0-9]+)\b(?<!' . implode('|', array_map('preg_quote', $ignoredWords)) . ')~i', $string);
answered 2010-01-16T21:13:02.533

Your Answer