5

I basically need a function to check whether a string's characters (each character) is in an array.

My code isn't working so far, but here it is anyway,

$allowedChars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","0","1","2","3","4","5","6","7","8","9"," ","@",".","-","_","+"," ");

$input = "Test";
$input = str_split($input);

if (in_array($input,$allowedChars)) {echo "Yep, found.";}else {echo "Sigh, not found...";}

I want it to say 'Yep, found.' if one of the letters in $input is found in $allowedChars. Simple enough, right? Well, that doesn't work, and I haven't found a function that will search a string's individual characters for a value in an array.

By the way, I want it to be just those array's values, I'm not looking for fancy html_strip_entities or whatever it is, I want to use that exact array for the allowed characters.

5 Answers 5

7

You really should look into regex and the preg_match function: http://php.net/manual/en/function.preg-match.php

But, this should make your specific request work:

$allowedChars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","0","1","2","3","4","5","6","7","8","9"," ","@",".","-","_","+"," ");
$input = "Test";
$input = str_split($input);
$message = "Sigh, not found...";
foreach($input as $letter) {
    if (in_array($letter, $allowedChars)) {
        $message = "Yep, found.";
        break;
    }
}
echo $message;
Sign up to request clarification or add additional context in comments.

Comments

4

Are you familiar with regular expressions at all? It's sort of the more accepted way of doing what you're trying to do, unless I'm missing something here.

Take a look at preg_match(): http://php.net/manual/en/function.preg-match.php

To address your example, here's some sample code (UPDATED TO ADDRESS ISSUES IN COMMENTS):

$subject = "Hello, this is a string";
$pattern = '/[a-zA-Z0-9 @._+-]*/'; // include all the symbols you want to match here

if (preg_match($pattern, $subject))
    echo "Yep, matches";
else
    echo "Doesn't match :(";

A little explanation of the regex: the '^' matches the beginning of the string, the '[a-zA-Z0-9 @._+-]' part means "any character in this set", the '*' after it means "zero or more of the last thing", and finally the '$' at the end matches the end of the string.

5 Comments

Ah, thank you, but when I run that it says that the - before the underscore gives it an error :( why is that? No I am not familiar with RegEx :P, well I have heard of it but I can't do it worth anything :P
This is not what he want. See "if one of the letters in $input is found in". To fix that, remove '^' and '$'.
Hmm, I've done that but it still gives me this error: Warning: preg_match() [function.preg-match]: Unknown modifier '-' in /home/jaxo/web/tests/test.php on line (line with preg_match statement)
how bout using a posix character class match like [:graph:] and from the looks of it [:blank:] or [:space:] for all of them see wikipedia
Right, sorry about that; I just wrote it without thinking too much about the expression. Yes, the '-' is invalid in a character class unless it comes at the beginning or the end (I've moved it to the end in the answer). Sorry for the trouble. :\
1

A somewhat different approach:

$allowedChars = array("a","b","c","d","e");
$char_buff = explode('', "Test");
$foundTheseOnes = array_intersect($char_buff, $allowedChars);
if(!empty($foundTheseOnes)) {
    echo 'Yep, something was found. Let\'s find out what: <br />';
    print_r($foundTheseOnes);
}

Comments

1

Validating the characters in a string is most appropriately done with string functions.
preg_match() is the most direct/elegant method for this task.

Code: (Demo)

$input="Test Test Test Test";
if(preg_match('/^[\w +.@_-]*$/',$input)){
    echo "Input string does not contain any disallowed characters";
}else{
    echo "Input contains one or more disallowed characters";
}
// output: Yes, input contains only allowed characters

Pattern Explanation:

/          # start pattern
^          # start matching from start of string
[\w +.@-]  # match: a-z, A-Z, 0-9, underscore, space, plus, dot, atsign, hyphen
*          # zero or more occurrences
$          # match until end of string
/          # end pattern

Significant points:

  • The ^ and $ anchors are crucial to ensure that the entire string is validated versus just a substring of the string.
  • The \w (a.k.a. "any word character" -> a shorthand character class) is the easy way to write: [a-zA-Z0-9_]
  • The . dot character loses its "match anything (almost)" meaning and becomes literal when it is written inside of a character class. No escaping slash is necessary.
  • The hyphen inside of a character class can be written without an escaping slash (\-) so long as the it is positioned at the start or end of the character class. If the hyphen is not at the start/end and it is not escaped, it will create a range of characters between the characters on either side of it.
    Like it or not, [.-z] will not match a hyphen symbol because it does not exist "between" the dot character and the lowercase letter z on the ascii table.
  • The * that follows the character class is the "quantifier". The asterisk means "0 or more" of the preceding character class. In this case, this means that preg_match() will allow an empty string. If you want to deny an empty string, you can use + which means "1 or more" of the preceding character class. Finally, you can be far more specific about string length by using a number or numbers in a curly bracketed expression.
    • {8} would mean the string must be exactly 8 characters long.
    • {4,} would mean the string must be at least 4 characters long.
    • {,10} would mean the string length must be between 0 and 10.
    • {5,9} would mean the string length must be between 5 and 9 characters.

All of that advice aside, if you absolutely must use your array of characters AND you wanted to use a loop to check individual characters against your validation array (and I certainly don't recommend it), then the goal should be to reduce the number of array elements involved so as to reduce total iterations.

  • Your $allowedChars array has multiple elements that contain the space character, but only one is necessary. You should prepare the array using array_unique() or a similar technique.
  • str_split($input) will run the chance of generating an array with duplicate elements. For example, if $input="Test Test Test Test"; then the resultant array from str_split() will have 19 elements, 14 of which will require redundant validation checks.
  • You could probably eliminate redundancies from str_split() by calling count_chars($input,3) and feeding that to str_split() or alternatively you could call str_split() then array_unique() before performing the iterative process.

2 Comments

This is a great answer, but I asked this question a little over 7 years ago! I hope it helps somebody in the future, though.
Yeah, that's all I was going for. Cheers.
0

Because you're just validating a string, see preg_match() and other PCRE functions for handling this instead.

Alternatively, you can use strcspn() to do...

$check = "abcde.... '; // fill in the rest of the characters
$test = "Test";
echo ((strcspn($test, $check) === strlen($test)) ? "Sigh, not found..." : 'Yep, found.');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.