Strpos with multiple characters

Hello,
I wuold create a condition with multpple characters in strpos. I’ve looked up on the php documentation but I’ve not found anything about it. So, is possibile realize that?

if (strpos($username,‘@ / & $ " !’) === false

Have tu use commas between every character?

Thank you in advance.

No I do not believe strpos() allows multiple search items… but that is easy to implement. Not the most elegant… but try this:


 
 $findMe = array('@', '/', '&', '$', '"', '!');
 
 $string = "fdfdfdf@asdfdsf$.jfdkjfd";
 
 echo multi_strpos($string, $findMe);
 
 
 /**
  * Returns position of needle, or false if not found
  * @param string $haystack The string that needs searched
  * @param array $needles An array of mixed values that we'll search for
  * @param integer $offset Offset position of search string (Optional)
  *
  * @return integer|false  false if not found
  */
 
 function multi_strpos($haystack, $needles, $offset = 0) {
 
 		foreach ($needles as $n) {
 			    if (strpos($haystack, $n, $offset) !== false)
 					    return strpos($haystack, $n, $offset);
 		}
 		return false;
 }
 
 

Thank you :slight_smile:

The one you’re looking for is [fphp]strcspn[/fphp]. Together with [fphp]strlen[/fphp] it does the job for you:


$BAD = "@$#\\"\\'";

$ok = strcspn("GoodBoy", $BAD) == strlen("GoodBoy");
// ---> TRUE

$ok = strcspn("Bad@Boy", $BAD) == strlen("Bad@Boy");
// ---> FALSE

However, the most common and conventional way to do the same is to use regular expressions:


$BAD = "@$#\\"\\'";
$BAD_REGEXP = "~[" . preg_quote($BAD) . "]~";

$ok = !preg_match($BAD_REGEXP, "GoodBoy");
// TRUE

$ok = !preg_match($BAD_REGEXP, "Bad@Boy");
// FALSE

That’s nice, but it’s easy to forget some “bad” char, therefore even better would be to list only “good” i.e. allowed chars:


$GOOD_REGEXP = "~[A-Za-z09]~";

$ok = preg_match($GOOD_REGEXP, "GoodBoy");
$ok = preg_match($GOOD_REGEXP, "Bad@Boy");