PHP Regex to allow special characters but no any space - php

I have the following Regex to allow alphanumeric characters and following special characters
/()-
The Regular expression is
/[^A-Za-z0-9-()-/]/
The complete method is
public function ValidateNumber($number)
{
$return = true;
$matches = null;
if((preg_match('/[^A-Za-z0-9-/()-]/', $number, $matches)) > 0)
{
$return = false;
}
return $return;
}
Above method woks fine, but also return TRUE if number has space. When i remove '/' from Regex then if number has 'space' in it then it returns FALSE.
So seems some issue with '/' in Regex.
Please advise some solution

Use this:
$theregex = '~^[a-z0-9/()-]+$~i';
if (preg_match($theregex, $yourstring)) {
// Yes! It matches!
}
else { // nah, no luck...
}
Explanation
The i flag at the end makes it case-insensitive
The ^ anchor asserts that we are at the beginning of the string
To match a hyphen in a [character class], place it at the beginning or at the end so that it is not ambiguous, since it may indicate a range, as in a-d
[a-z0-9/()-]+ matches one or more letter, digit, slash, parenthesis or hyphen
The $ anchor asserts that we are at the end of the string

Regex to allow alphanumeric characters and the the above mentioned special characters /()-,
^[A-Za-z0-9()\/-]+$
^ inside(at the strat of) chracter class means not. So your regex allows any character not of the ones mentioned inside the character class. And also it's better to escape / inside the character class and always consider in putting - at the start or end of the character class. To allow one ore more characters which was mentioned inside char class then you need to add + after the character class.
Explanation:
^ the beginning of the string
[A-Za-z0-9()\/-]+ any character of: 'A' to 'Z', 'a' to 'z',
'0' to '9', '(', ')', '\/', '-' (1 or more
times)
$ before an optional \n, and the end of the
string

You should escape / in your regex using \/
But you should probably use the following expression to do what you want:
([^A-Za-z0-9-()-\/])+
So the whole method could look like this:
public function ValidateNumber($number)
{
if (preg_match('/([^A-Za-z0-9-()-\/])+/', $number)) {
return false;
}
return true;
}
without extra variables.
In above case you try to find any characters that don't match (here ^ means characters that don't match) your criteria and if any of them is found preg_match return 1 so it means that number is invalid.
However you can also use another expression to achieve what you want - you don't find characters that don't match (as in previous example) but you check if the whole string matches your criteria using ^ as the beginning (in this case it means the beginning of the string - meaning is different that the one in previous solution) and $ as the end of the string to check the whole string. In this case your method could look like this:
public function ValidateNumber($number)
{
if (preg_match('/^([A-Za-z0-9-()-\/]+)$/', $number)) {
return true;
}
return false;
}

For Much better understanding and learning regex for the further work you can visit the below links
Learning Regular Expressions
Useful regular expression tutorial
Regular expressions tutorials
And one of the best and easy one and my favourite is
http://www.9lessons.info/2013/10/understanding-regular-expression.html?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+9lesson+%289lessons%29
very nice and easy tutorial for the beginners

Related

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

How can I find Alphanumeric in a string

$foo = "username122";
pre_match('Contain only aplhanumeric string', $foo){
return true;
}
$foo Contain Only alphanumeric not special characters (=\*-[( etc)
ctype_alnum() function will do you dandy :)
Use a regular expression matching on alphanumeric characters only from beginning to end:
/^[A-Za-z0-9]*$/
For example:
$testRegex = "/^[A-Za-z0-9]*$/";
$testString = "abc123";
if (preg_match($testRegex, $testString)) {
// yes, the string is entirely alphanumeric
} else {
// no, the string is not entirely alphanumeric
}
if(preg_match('~[^a-z0-9 ]~i', $foo)) {
//DO SOMETHING HERE;
}
Your regular expression for something like this won't change between PHP and JavaScript. In JavaScript it's an object, whereas in PHP it's a string, but the pattern is still the same:
/^[a-z0-9]+$/i
Where ^ represents the start of the string and $ represents the end of the string. Next, a-z matches any letter, and 0-9 matches any number. The + states that the previous pattern could be repeated one or more times. The i modifier makes the a-z portion case-insensitive, so upper and lower case are matched.
Testing in JavaScript:
/^[a-z0-9]+$/i.test("Foo123"); // true
Testing in PHP:
preg_match("/^[a-z0-9]+$/i", "Foo123"); // 1
With PHP, you have the option of using POSIX character classes, such as :alnum:. Please note that this won't work in JavaScript:
preg_match("/^[[:alnum:]]+$/i", "Foo123"); // 1
There's actually a much easier method for testing in PHP, using the Ctype functions, specifically the ctype_alnum function, which will return a boolean value stating whether all characters in a given string are alphanumeric or not:
ctype_alnum("Foo123"); // true
ctype_alnum("Foo!23"); // false

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.

How to check if a string is in an array?

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

PHP Regular Expression. Check if String contains ONLY letters

In PHP, how do I check if a String contains only letters? I want to write an if statement that will return false if there is (white space, number, symbol) or anything else other than a-z and A-Z.
My string must contain ONLY letters.
I thought I could do it this way, but I'm doing it wrong:
if( ereg("[a-zA-Z]+", $myString))
return true;
else
return false;
How do I find out if myString contains only letters?
Yeah this works fine. Thanks
if(myString.matches("^[a-zA-Z]+$"))
Never heard of ereg, but I'd guess that it will match on substrings.
In that case, you want to include anchors on either end of your regexp so as to force a match on the whole string:
"^[a-zA-Z]+$"
Also, you could simplify your function to read
return ereg("^[a-zA-Z]+$", $myString);
because the if to return true or false from what's already a boolean is redundant.
Alternatively, you could match on any character that's not a letter, and return the complement of the result:
return !ereg("[^a-zA-Z]", $myString);
Note the ^ at the beginning of the character set, which inverts it. Also note that you no longer need the + after it, as a single "bad" character will cause a match.
Finally... this advice is for Java because you have a Java tag on your question. But the $ in $myString makes it look like you're dealing with, maybe Perl or PHP? Some clarification might help.
Your code looks like PHP. It would return true if the string has a letter in it. To make sure the string has only letters you need to use the start and end anchors:
In Java you can make use of the matches method of the String class:
boolean hasOnlyLetters(String str) {
return str.matches("^[a-zA-Z]+$");
}
In PHP the function ereg is deprecated now. You need to use the preg_match as replacement. The PHP equivalent of the above function is:
function hasOnlyLetters($str) {
return preg_match('/^[a-z]+$/i',$str);
}
I'm going to be different and use Character.isLetter definition of what is a letter.
if (myString.matches("\\p{javaLetter}*"))
Note that this matches more than just [A-Za-z]*.
A character is considered to be a letter if its general category type, provided by Character.getType(ch), is any of the following: UPPERCASE_LETTER, LOWERCASE_LETTER, TITLECASE_LETTER, MODIFIER_LETTER, OTHER_LETTER
Not all letters have case. Many characters are letters but are neither uppercase nor lowercase nor titlecase.
The \p{javaXXX} character classes is defined in Pattern API.
Alternatively, try checking if it contains anything other than letters: [^A-Za-z]
The easiest way to do a "is ALL characters of a given type" is to check if ANY character is NOT of the type.
So if \W denotes a non-character, then just check for one of those.

Categories