preg_match exclude characters???

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
peterro
Forum Newbie
Posts: 3
Joined: Fri May 12, 2006 11:30 am

preg_match exclude characters???

Post by peterro »

Howdy All:

I am trying to write a regular expression to basically process dvd titles. For example if I have

The Great Mouse Detectives I would like to display Great Mouse Detectives, The

I have a function that does almost what I need but when there is a special character i.e( .,!@#$%...) it breaks.

A.I. Artificial Intelligence => .I. Artificial Intelligence, A

Is there a way that I can get preg_match to exclude a set of characters after it matches the ‘A’?

preg_match("/\b$needle\b/i", strtolower($haystack))

$needle is ‘a’ or ‘an’ or ‘the’ and $haystack is the original title.

Any help would be awesome!!!
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

Moved to Regex
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Artificial Intelligence?

Post by tr0gd0rr »

Simple Solution might be

Code: Select all

preg_match("/^(a|an|the) /i", strtolower($haystack))
which would match "A Tale of Two Cities" but not "A.I. Artificial Intelligence".


but you can also do a negative lookahead, which is what you are asking:

Code: Select all

preg_match("/^(a|an|the)(?!$exclude)/i", strtolower($haystack))
where $exclude is a character or character class to exclude. If $exclude = "\.", the regex will match "A Tale of Two Cities" but not "A.I. Artificial Intelligence".
Post Reply