Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains only specific characters

Tags:

php

preg-match

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.

like image 845
Damon Avatar asked Apr 20 '12 14:04

Damon


2 Answers

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

or:

if (strlen(str_replace('|', '', $string)) > 0) {
    // string contains characters other than |
}
like image 193
deceze Avatar answered Oct 15 '22 19:10

deceze


Yes, you can use regular expressions:

if(! preg_match('/[^\|]/', $string)) {
  $string = NULL;
}
like image 34
Husman Avatar answered Oct 15 '22 17:10

Husman