How to check if a string is in an array? - php

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.

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;

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.

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);
}

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.

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.');

Related

Finding presence of chars or strings out of the allowed ones

Well, I'm stuck, I cannot find the correct form for the RegEx to provide to the PHP preg_match.
I have two strings. Say "mdo" and "o", but they could be really random.
I have a dictionary of allowed chars and strings.
For the example, allowed chars are "a-gm0-9", and allowed strings are "do" and "si".
THE GOAL
I'm trying to check that the input string doesn't contain any char or string but those in the dictionary, case-insensitive.
So the case of "mdo" wouldn't match because m is allowed just like the string do. Not the same for o instead, which has o that is not an allowed char and which doesn't contain the whole allowed string do.
My struggling reason
It's ok to negate [^a-gm0-9] and (?!do|si), but what I cannot achieve is to place them inside a single regex in order to apply the following PHP code:
<?php
$inputStr = 'mdo';
$rex = '/?????/i'; // the question subject
// if disallowed chars/strings are found...
if( preg_match($regex, $inputStr) == 1 )
return false; // the $inputStr is not valid
return true;
?>
Because two cascading preg_matches would break the logic and don't work.
How to mix chars check and groups check in "AND" in a single regex? Their positions don't matter.
You can use this pattern:
return (bool) preg_match('~^(?:do|si|[a-gm0-9])*+\C~i', $inputStr);
The idea is to match all allowed chars and substrings from the start in a repeated group with a possessive quantifier and to check if a single byte \C remains. Since the quantifier is greedy and possessive, the single byte after, if found, can't be allowed.
Note that most of the time, it is more simple to negate the preg_match function, example:
return (bool) !preg_match('~^(?:do|si|[a-gm0-9])*$~iD', $inputStr);
(or with a + quantifier, if you don't want to allow empty strings)

PHP Regex Strip Away All Emojis

I am trying to strip away all non-allowed characters from a string using regex. Here is my current php code
$input = "👮";
$pattern = "[a-zA-Z0-9_ !##$%^&*();\\\/|<>\"'+\-.,:?=]";
$message = preg_replace($pattern,"",$input);
if (empty($message)) {
echo "The string is empty";
}
else {
echo $message;
}
The emoji gets printed out when I run this when I want it to print out "The string is empty.".
When I put my regex code into http://regexr.com/ it shows that the emoji is not matching, but when I run the code it gets printed out. Any suggestions?
This pattern should do the trick :
$filteredString = preg_replace('/([^-\p{L}\x00-\x7F]+)/u', '', $rawString);
Some sequences are quite rare, so let's explain them:
\p{L} matches any kind of letter from any language
\x00-\x7F a single character in the range between (index 0) and (index 127) (case sensitive)
the u modifier who turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject strings are treated as UTF-8.
Your pattern is incorrect. If you want to strip away all the characters that are not in the list provided, then you have to use a negating character class: [^...]. Also, currently, [ and ] are being used as delimiters, which means, the pattern isn't seen as a character class.
The pattern should be:
$pattern = "~[^a-zA-Z0-9_ !##$%^&*();\\\/|<>\"'+.,:?=-]~";
This should now strip away the emoji and print your message.

regex to validate first name excluding #()&

I am looking to create Regex for the first name which can allow all the special characters except #()&, I am trying to implement it in PHP i tried something like
/^[^0-9\#\(\)\&][a-zA-Z\s]*$/ but its not validating properly .
If your intention was to allow special characters (other than those four) anywhere in the string, then your pattern is wrong.
I'll break down your pattern to walk you through what it does:
^ - The match must begin at the start of a line (or entire string).
[^0-9\#\(\)\&] - Match any single character which is not a number, an #, a parenthesis, or an ampersand. I'm pretty sure the slashes here are superfluous, by the way. The ones before the # and & characters almost certainly are, since those characters aren't ever special inside regexes. The ones before the ( and ) might be needed, since those characters are the subpattern delimiters, but I think they're still unneeded here since they're inside a character class.
[a-zA-Z\s]* - Match any lower or uppercase character between A and Z, or any whitespace character, like a space (this is what \s does). The * means you can match as many of these characters as there are in a row, or no characters if none of them exist in this position.
$ - The match must end at the end of the line (or entire string).
In short, you're only excluding those four special characters from the first character of your string, but you're exluding all special characters as any character after the first.
If you want to allow any character, except those four, in any position in the string, then you should use this as your pattern:
/^[^0-9#&()]*$/
With all of that said, I think you might be overcomplicating things a bit. It's sort of a matter of opinion, but I try to only use regular expressions when there is no other way to do something, since they can be a bit hard to read (this question is a good example of that).
What I would suggest is that you just use str_replace to remove the four characters you're disallowing, and check the resultant string against your original input:
if($input === str_replace(array('#', '&', '(', ')'), '', $input) {
// process valid input
} else {
// handle invalid input
}
The str_replace call will take your original string and replace any value in the search array, array('#', '&', '(', ')'), and remove it (technically, "replace" it with nothing). If the two strings match after that, then none of the invalid characters were present, and your input is valid.
Since you're using parentheses as items within the array, it might be more readable to separate the elements onto their own lines:
$chars_to_remove = array(
'#',
'&',
'(',
')'
);
if ($input === str_replace($chars_to_replace, '', $input)) {
// process valid input
} else {
// handle invalid input
}
FirstName <input type=text name="fname" onblur="first(this)" />
function first(ev) {
var val = ev.value;
if(isNaN(val)) {
for(var i = 0; i < 10; i++) {
if(val.indexOf(i) != -1) {
alert("Enter Only chars");
return false;
}
}
}
else {
alert("Enter Only chars");
}
return true;
}

`preg_match` the Whole String in PHP

This thing really confuses me, pardon my ignorance.
I have a var $name in here that I want to be free from number, I don't want any digit to be included in it. My preg_match() is this:
var_dump(preg_match('/[^\d]/',$name));
Test cases:
$name = "213131"; // int(0)
$name = "asdda"; // int(1)
$name = "as232dda"; // int(1)
What I want is to have the third case to be int(0) too.
I'm really a hard time understanding this preg_match(), docs say it return 1 if a pattern match a subject. Here in my case, I use a negated class.
#3 matches because you have both letters and numbers. Your regex in English basically says
it matches if there is a non-digit character
If you want to match only non-digit characters, you have to have the regex match against the entire string and allow for an arbitrary number of characters:
^[^\d]+$
Your regex only checks that there is at least one non-digit. Instead, you need to check that it is only non-digits:
var_dump(preg_match('/^\D+$/',$name));
(^ and $ are the beginning and end of the string. \D means anything not a digit--the opposite of \d. So this only matches non-digits from beginning to end. It doesn't match an empty string. Replace + with * if you want to match an empty string as well).
Try this:
<?php
$string = "as232dda";
$new_string = trim(str_replace(range(0,9),'',$string));
echo $new_string;// gives 'asdda'
?>
Or function form:
<?php
function remove_numbers($string){
return(trim(str_replace(range(0,9),'',$string)));
}
$string = "as232dda";
echo remove_numbers($string); // gives 'asdda'
?>

Php Sanitize and Validate form with some character exceptions

I'm using in Php Sanitize and Validate Filters but I have problems to add some rules, I have some basic knowledge of php so I think this question is easy for you.
if ($_POST['ccp_n'] != "") {
$ccp = filter_var($_POST['ccp_n'], FILTER_SANITIZE_NUMBER_INT);
if (!filter_var($ccp, FILTER_VALIDATE_INT)) {
$errors .= 'Insert a valid code.<br/>';
}
} else {
$errors .= 'Insert a code.<br/>';
}
I need to add a minimum and maximum number of characters (14-15) and I want to accept this characters ( - or space ) .The exact sequence is 0000-0000-0000 (the last four digits could be 5 too
Thanks
You can use preg_match and apply a regular expression.
preg_match ( string $pattern , string $TestString) See here in detail
The pattern is the problem. You need to define in detail what is allowed.
For example, the pattern:
'~^\d{4}-\d{4}-\d{4,5}$~D'
would be the whole string from start ^ to the end $. 4 digits, hyphen, 4 digits, hyphen, 4 to 5 digits.
See it here on Regexr
Update:
I added the D modifier to the end, otherwise the $ not only match to the end of the string, but also before a newline as last character in the string. See here for php modifiers in detail
Use a regular expression with preg_match(). Alternatively, you can also use sscanf() to parse the input from a string according to a format.

Categories