I have the following string:
$cadena = "samu,miguel,pedro,samuel";
$idUsuario = "samu";
And the following condition:
if (stripos($cadena, $idUsuario) !== false){
echo 'Estás en el grupo';
}else{
echo "No estás en el grupo";
}
The problem is that if the string contains a name that also starts with samu , such as ' samuel ', the program will detect it as true.
What I want is that if the $idUsuario=' samu ' does NOT detect other similar ones, but it is exactly ' samu '
If there is another way to make what I want to achieve more effective, I would appreciate it in advance.
If the format of your variables is correct (that the independent string is separated by commas and the dependent string is not) then you can do it in two different ways.
Method 1: Regular Expressions
The advantage of regular expressions is that you can create them in a static or dynamic way, for example for the variables that you put the following could work
What you are telling it is any string that starts with or without a space and contains
samu
and ends with or without a space and ends with or without a comma, if you notice the question mark means that a character is optional.Now if you put this with variables it would be as follows
Once you have that you must continue with the validation, for this you must do it with
preg_match()
orpreg_match_all()
which will return a match with the regular expression.Now your validation would be as follows
With this you can use regular expressions for your validations.
Method 2: split and iteration
Method two is simpler but it only works if your values are separated by a comma or some identifier.
Using the function
explode()
you can split a string into substrings and store it in an array, looking more or less like thisMethod 1 references
regex101 - Here you can test your regular expressions
preg_match
preg_match_all
References method 2
explode()