Why doesn't this array search work for me?
I have a simple array search I'm doing with php.
$qs = 'something$';
// check if string has bad characters...
$bad_chars = array('$',',',' ','?','=','&','-','|','@','#','%','^','*','(',')','{','}','|','\\','[',']','/','`','~');
if(in_array($qs,$bad_chars)) {
echo 'bad characters';
}
To me, th开发者_运维知识库is should echo 'bad characters', but it doesn't.
What am I missing?
UPDATE: benchmark, comparing the 4 answers with code:
100,000 iterations over the test_bad_charachters function, no output:
Jason's answer (for/str/in_array
): 32 sec
Mike Lewis' answer (foreach/str_split/in_array
): 23 sec
Gaurav's answer (array_intersect/!=
): 8 sec
my answer (str_replace/==
): 4 sec
UPDATE END
as the other answers point out, in_array($qs, $bad_chars)
does not test if the characters of $qs
are in $bad_chars
, but the whole string $qs
(which obviously it is not). to get the expected result, you have to test the single characters of $qs
.
here is a solution that should do this fast:
<?php
$qs = 'something$';
// bad characters
$bad_chars = array('$',',',' ','?','=','&','-','|','@','#','%','^','*','(',')','{','}','|','\\','[',']','/','`','~');
// replace all bad characters in $qs with \00. if the resulting string
// differs from the original string, it has bad characters.
// using a single call to str_replace should make this faster than all
// other suggested solutions - see the benchmark in the UPDATE.
if (str_replace($bad_chars, '\0', $qs) == $qs) {
echo 'bad characters';
}
$array = str_split($qs);
if(array_intersect($array, $bad_chars) != array())
{
echo 'bad characters';
}
Just look at each letter individually instead of the word as a whole.
$qs = 'something$';
$bad_chars = array('$',',',' ','?','=','&','-','|','@','#','%','^','*','(',')','{','}','|','\\','[',']','/','`','~');
for($i=0; $i < strlen($qs); $i++) {
// check if string has bad characters...
if(in_array($qs[$i],$bad_chars)) {
echo 'bad characters';
}
}
This is because it is seeing if "something$" is an element in $bad_chars, which it isn't.
Edit:
Solution:
<?php
$qs = 'something$';
// check if string has bad characters...
$bad_chars = array('$',',',' ','?','=','&','-','|','@','#','%','^','*','(',')','{','}','|','\\','[',']','/','`','~');
foreach(str_split($qs) as $char){
if(in_array($char, $bad_chars)){
echo $char. " was bad char";
}
}
?>
you are searching for the full "something$"'
, not just the bad "$"
- this is why.
look for doc in http://php.net/in_array .
精彩评论