Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check a string for multiple certain characters?

I have a string and I need to check it for several characters. I can do that with strpos();. But in this case, I would need to use strpose(); several times. something like this:

$str = 'this is a test';
if(
   strpos($str, "-") === false &&
   strpos($str, "_") === false &&
   strpos($str, "@") === false &&
   strpos($str, "/") === false &&
   strpos($str, "'") === false &&
   strpos($str, "]") === false &&
   strpos($str, "[") === false &&
   strpos($str, "#") === false &&
   strpos($str, "&") === false &&
   strpos($str, "*") === false &&
   strpos($str, "^") === false &&
   strpos($str, "!") === false &&
   strpos($str, "?") === false &&
   strpos($str, "{") === false &&
   strpos($str, "}") === false 
  )
    { do stuff }

Now I want to know, is it possible to use a regex to define my condition summary?


Edit: here is some examples:

$str = 'foo'     ----I want this output---> true
$str = 'foo!'    -------------------------> false
$str = '}foo'    -------------------------> false
$str = 'foo*bar' -------------------------> false

and so on. In other word, I want just text character: abcdefghi... .

like image 341
Shafizadeh Avatar asked Jan 08 '23 21:01

Shafizadeh


2 Answers

You could use a basic regex:

$unwantedChars = ['a', '{', '}'];
$testString = '{a}sdf';

if(preg_match('/[' . preg_quote(implode(',', $unwantedChars)) . ']+/', $testString)) {
    print "Contains invalid characters!";
} else {
    print "OK";
}
like image 99
t.h3ads Avatar answered Jan 18 '23 14:01

t.h3ads


Use negative lookahead assertion.

if (preg_match("~^(?!.*?[-_^?}{\]\[/'@*&#])~", $str) ){
// do stuff
}

This will do the stuff inside braces only if the string won't contain anyone of the mentioned characters.

If you want the string to contain only word chars and spaces.

if (preg_match("~^[\w\h]+$~", $str)){
// do stuff
}

or

AS @Reizer metioned,

if(preg_match("~^[^_@/'\]\[#&*^!?}{-]*$~", $str)){

Replace the * (present next to the character class) in the above with +, if you don't want to match an empty string.

For only alphabets and spaces.

if(preg_match("~^[a-z\h]+$~i", $str) ){
like image 28
Avinash Raj Avatar answered Jan 18 '23 13:01

Avinash Raj