Page 1 of 1

preg_match unknown modifier '|' (pipe)

Posted: Mon Sep 21, 2009 10:31 pm
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

/[!|\@|#|\\|/|\^|\+|\(|\)|\[|\]|\.|,|\$|\?|<|>|{|}|\||-|=|~|\`]/

Re: preg_match unknown modifier '|' (pipe)

Posted: Tue Sep 22, 2009 10:30 am
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/