How to check if a string contains only certain characters

I need to check a string to determine if it contains any characters other than | to assign variables that have nothing but | NULL values ​​(theoretically, there can be any number of | characters, but this is most likely no more than 5-6). How ||||

I could see a scrolling of each character of the string or something like this, but I believe there should be an easier way.

+6
source share
4 answers
 if (preg_match('/[^|]/', $string)) { // string contains characters other than | } 

or

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

Yes, you can use regular expressions:

 if(! preg_match('/[^\|]/', $string)) { $string = NULL; } 
+2
source

I wanted to check if a string contains only certain characters. To prevent double negation (because I find them harder to read), I decided to use the following regular expression:

 preg_match('/^[|]+$/', $string) 

This checks the string from beginning to end to contain only characters | (at least one).

+1
source

The fastest and easiest way is perhaps the stripos function. It returns the position of the string inside another or false if it cannot be found:

 if (false === stripos($string, '|')) { $string = null; } 

Strict type comparisons require false === , since stripos can return zero, indicating that | located on the first char.

You can use a more sophisticated check mechanism that makes reading easier. I recommend Respect \ Validation . Usage example:

 if (v::not(v::contains('|'))->validate($string)) { $string = null; } 
0
source

Source: https://habr.com/ru/post/913732/


All Articles