Forum Moderators: coopster
I am trying to filter out strings that have specific characters. I have this:
$chars = array("#","(","[","+","'","/","&","!","%");
(below code is in a for loop)
if (strpos($title[$i],$chars) > -1) {
$title[$i] = false;
} else {
...............
My problem is I can't get it to filter any of the characters in the $chars variable. No error comes up, it just doesn't do it.
Now, if I have:
if (strpos($title[$i],"#") > -1 ¦¦ strpos($title[$i],"(") > -1 ¦¦ strpos($title[$i],"[") > -1) {
$title[$i] = false;
} else {
...............
The long inefficient way works... and I have about 20 ¦¦'s ... I imagine it would use a lot of CPU and the first way (with array) looks much better. Can I get the first way working? I have tried so many things. Any help MUCH appreciated.
I'm not sure if the strpos function can check arrays, but please do not quote me on that =)
The additional way to do this would be to loop through all the items in the array and use the strpos repeatidly, like so.
$chars = array("#","(","[","+","'","/","&","!","%");
$title[$i] = "This has a hash #";$chars = array("#","(","[","+","'","/","&","!","%");
foreach ($chars as $badChar)
{
if (strpos($title[$i], $badChar) > -1)
{
$title[$i] = false;
break;
}
}
This should work, please note it is untested, it will set the $title[$i] to false if the char is found in the string.
You can the validate after if this string is a good or a bad one.
e.g.
if ($title[$i] === false)
{
// It has the bad character
}
else
{
// It's clean
}
Good luck
Del
if (array() !== [url=http://www.php.net/manual/en/function.array-intersect.php]array_intersect[/url]([url=http://www.php.net/manual/en/function.str-split.php]str_split[/url]($title[$i]), $chars)) {// $title[$i] contains something in $chars} else {// ...}Splits the string into an array of characters and sees if any of those characters match the characters in your $chars array. -or-
char_re = '/['.[url=http://www.php.net/manual/en/function.preg-quote.php]preg_quote[/url](join('', $chars), '/').']/'; // ... if ([url=http://www.php.net/manual/en/function.preg-match.php]preg_match[/url]($char_re, $title[$i])) {// $title[$i] contains something in $chars} else {// ...} I'm using:
$char_re = '/['.preg_quote(join('', $chars), '/').']/';
// ...
if (preg_match($char_re, $title[$i])) {// $title[$i] contains something in $chars
} else {
// ...
}
It's working really well.
Regarding CPU usage, is the above more efficient than using what I originally had?
Eg: if (strpos($title[$i],"#") > -1 ¦¦ strpos($title[$i],"(") > -1 ¦¦ strpos($title[$i],"[") > -1) {
$title[$i] = false;
} else {
...............