Search code examples
phpstringvalidationpreg-matchwhitelist

How to check if a string contains only specific characters


I need to check a string to determine if it contains any characters other than |, in order to assign those variables that have nothing except | a value of NULL (there could be theoretically any number of | characters but it likely will not be more than 5-6). Like ||||

I could see looping through each character of the string or somesuch, but I feel there must be a simpler way.


Solution

  • if (preg_match('/[^|]/', $string)) {
        // string contains characters other than |
    }
    

    or:

    if (strlen(str_replace('|', '', $string)) > 0) {
        // string contains characters other than |
    }