Shafizadeh
Shafizadeh

Reputation: 10340

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... .

Upvotes: 4

Views: 5216

Answers (3)

Konstantin
Konstantin

Reputation: 566

May be something like that:

function strpos_multi(array $chars, $str) {
  foreach($chars as $char) {
    if (strpos($str, $char) !== false) {
      return false;
    }
  }
  return true;
}

$res = strpos_multi(["-", "_", "@", "/", "'", "]", "[", "#", "&", "*", "^", "!", "?", "{", "}"], $str);
if ($res) {
  //do some stuff
}

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174696

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) ){

Upvotes: 3

t.h3ads
t.h3ads

Reputation: 1878

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";
}

Upvotes: 4

Related Questions