preg_match unknown modifier '|' (pipe)

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

Moderator: General Moderators

Post Reply
Cirdan
Forum Contributor
Posts: 144
Joined: Sat Nov 01, 2008 3:20 pm

preg_match unknown modifier '|' (pipe)

Post by Cirdan »

I'm trying to write a method that checks for special characters in a given string, however it says that the pipe character is an unknown modifier :?:

Code: Select all

   public static function hasSpecialCharacters($string) {
        // checking for special characters
        $specialChars = array('!', '\@', '#', '\\\\', '/', '\^', '\+', 
                                '\(', '\)', '\[', '\]', '\.', ',', '\$', '\?',
                                '<', '>', '{', '}', '\|', '-', '=', '~', '\`' );
        $regex ='/[';
        
        $last = end($specialChars);
        foreach($specialChars as $char) {
            $regex .=  $char;
            
            if($char != $last)
                $regex .= '|';
        }
        $regex .=']/';
 
        if(preg_match($regex, $string)) {
            return true;
        }
        
        return false;
    }
The created regex:

Code: Select all

/[!|\@|#|\\|/|\^|\+|\(|\)|\[|\]|\.|,|\$|\?|<|>|{|}|\||-|=|~|\`]/
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: preg_match unknown modifier '|' (pipe)

Post by ridgerunner »

You are escaping characters in the character class that don't need to be escaped ('@^+()[.$?|') and you are failing to escape characters that do need to be escaped ('-/'). You are using the forward slash '/' as the regex delimiter, so this character needs to be escaped. The reason you are getting the warning is because the regex delimiter '/' appears in an unescaped form inside the character class and is immediately followed by the pipe char which the regex engine is interpreting to be the first regex modifier. Here is a corrected regex:

Code: Select all

$regex = '%[!@#\\\\/^+()[\].,$?<>{}|\-=~`]%'
Also, you are erroneously separating characters in a character class with the pipe character '|'. These are very fundamental errors and you would be well advised to read a tutorial on regex! see: http://www.regular-expressions.info/
Post Reply