How to check if a string contains only specific characters

Damon picture Damon · Apr 20, 2012 · Viewed 17.4k times · Source

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.

Answer

deceze picture deceze · Apr 20, 2012
if (preg_match('/[^|]/', $string)) {
    // string contains characters other than |
}

or:

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