I've wrote a simple function to check if the string I send "should be" valid or not.
// this works without problems
function validate_email ($value) {
return preg_match ("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/", $value);
}
// this doesn't work
function validate_string ($value) {
return preg_match ("([^<>?=/\]+)", $value);
}
the first function works well, if I send an email to validate_email I'm used to retain valid it return me 1 or 0 if not.
validate_string should do the same with strings of every kind but without ? = < > / \. If I check the function it return me 1 in anycase, why?
validate_string ("tonino"); // return 1 ok
validate_string ("ton\ino\"); // return 1 why?
validate_string ("ton?asd=3"); // return 1 why?
the ^ char inside ([^<>?=/]+) should mean not the chars after (or not?)
You aren't matching the beginning (^) and end ($) of the string. So "ton?asd=3" matches because the pattern matches t (and the rest of the string is irrelevant).
There are several errors in your code. Besides that "ton\ino\" is not a valid string and [^<>?=/\]+ is not a valid regular expression, you have probably some logical misunderstanding.
Your regular expression [^<>?=/\\]+ (here corrected) will match if there is at least one character that is not <, >, ?, =, / and \. So if there is at least one such character, preg_match returns 1. ton\ino" and ton?asd=3 do both contain at least one such character (the match is in both cases ton).
A fix for this is to either use assertions for the start and end of the string (^ and $) to only allow legal characters for the whole string:
^[^<>?=/\\]+$
Or to use a positive character class [<>?=/\\]+ to match the illegal characters and negate the returned expression of preg_match:
function validate_string ($value) {
return !preg_match("([<>?=/\\\\]+)", $value);
}
But it would be certainly better to use a whitelist instead of a blacklist.
\ is a meta character, you need to escape it. So it would be
return preg_match ("([^<>?=/\\\\]+)", $value);
function validate_string ($value) {
return !preg_match('#[<>?=/\\\\]#', $value);
}
Related
Like the title says, I'm looking for a way to check if a string contains an uppercase letter in it. It is for a password field, and I cannot use regex because we have not learned any of that yet in class.
I tried to use ctype_upper but that only seems to work if every character in the string is uppercase.
Is there a way to check any character in a string, but not using regex?
You can try this:
if (strtolower($string) != $string) {
echo 'You have uppercase in your string';
} else {
echo 'You have no uppercase in your string';
}
This checks if the converted string to lowercase is equal to the original string. Hope this helps...
Try this..
Use the strtoupper() function to transform the string into all uppercase characters that’s capitalized letters, and then compare the transformed string against the original one to see if they are identical. If they are, then you are pretty sure the original string was also a string consisting of ONLY capital letters
if (strtoupper($string) == $string) {
echo $string.' is all uppercase letters.';}
function isPartUppercase($string) { if(preg_match("/[A-Z]/", $string)===0) { return true; } return false; }
The function uses a simple regular expression that tries to find any upper case A-Z characters, preg_match() returns the number of instances of the expression it finds in the string, but stops at 1, preg_match_all() returns the count of all instances it finds.
I have written the following code to check if the given string is Latin or it contains some other non-latin chars like Persian. The issue is that it always returns true for both of the following strings:
$str = "Hello, What's up?"
Or
$str = "Hello, سلام"
While for the second string it should return false since it contains Persian characters (non-latin) too.
$default_rule = "/[a-zA-Z0-9\(\)\*_\-\!\#\$\%\^\&\*\,\.\"\'\]\[]*/";
$rule = ($rule==null) ? $default_rule : $rule;
if(preg_match($rule, $str)==true)
{
// always returns true
}
Your pattern will return true if the string contains zero or more of those characters you've specified. In other words, it will return true for any string at all. You need to put start (^) and end ($) anchors around it. Also you don't need to escape most of those characters (the character class causes them to be treated as literal characters):
$default_rule = '/^[a-zA-Z0-9()*_\-!#$%^&*,."\'\][]*$/';
But, this will match an empty string. To also make sure that the string is not empty, use the + quantifier (one or more) instead of *.
$default_rule = '/^[a-zA-Z0-9()*_\-!#$%^&*,."\'\][]+$/';
I have been trying to figure this out really hard and I cannot came out with a solution ,
I have an arrary of strings which is
"Descripcion 1","Description 2"
and I need to filter by numbers, so I thought maybe I can use preg_match() and find when there is exactly 1 number 1 or two or etc, and do my logic, becouse the string before the number may change, but the number cannot, I have tried using
preg_match(" 1{1}","Description 1")
which is suppossed to return true when finds an space followed by the string "1" exactly one time but returns false.
Maybe some of you have had more experience with regular expressions in php and can help me.
Thank you very much in advance.
You could use strpos instead of preg_match!
foreach($array as $string) {
if(strpos($string, ' 1') !== false) {
//String contains " 1"!!
}
}
This would be much faster then a regular expression.
Or, if the Number has to be at the end of the string:
foreach($array as $string) {
if(substr($string, -2) == ' 1') {
//String ends with " 1"!!
}
}
You forgot the regex delimiters. Use preg_match('/ 1/', ...) instead.
However, you do not need a regex at all if you just want to test if a string is contained within another string! See Lars Ebert's answer.
You might have success using
if (preg_match('/(.*\s[1])/', $var, $array)) {
$descrip = $array[1];
} else {
$descrip = "";
}
I tested the above regex on the 3 separate string values of descripcion 1, thisIsAnother 1, andOneMore 1. Each were found to be true by the expression and were saved into group 1.
The explanation of the regex code is:
() Match the regular expression between the parentheses and capture the match into backreference number 1.
.* Match any single character that is not a line break character between zero and as many times possible (greedy)
\s Match a single whitespace character (space, tab, line break)
[1] Match the character 1
I have this function:
function validate_string_spaces_only($string) {
if(preg_match("/^[\w ]+$]/", $string)) {
return true;
} else {
return false;
}
}
I want to match a string that consists only of letters and numbers with an optional space character. When I feed the above function a string containing only letters, numbers and spaces it fails every time. What am I missing?
You have an extra ] character in your regex near the end. Remove it and it should work.
"/^[\w ]+$]/" should be "/^[\w ]+$/".
(Also note that \w typically allows underscores as well, which you may or may not want.)
This regex will:
match a string that consists only of letters and numbers with an optional space character
^[a-zA-Z0-9\s]+$
Is it possible to validate input depending on whether it only contains a combination of letters, numbers and hyphens (where a hyphen is not repeated twice-in-a-row and does not begins/ends the string)?
Thanks to Validate username as alphanumeric with underscores
I know that the following validates a string based on alphanumeric input with underscores, would it be possible to alter this?
function validate_alphanumeric_underscore($str)
{
return preg_match('/^[a-zA-Z0-9_]+$/',$str);
}
Thank you in advance for your help!
This can be done quite easily with a single regular expression:
/^([a-z0-9]+-)*[a-z0-9]+$/i
This meets all your criteria:
No double hyphens
No beginning/ending hyphens
Works when strlen == 1
Matches:
a
a-a
a-a-a
Doesn't match:
-
a-
-a
a--a
a-a--a
Play with it here.
Assuming a minimum of 2 characters:
This will validate the general format (not starting or ending with a -).
/^[a-z0-9][a-z0-9-]*[a-z0-9]$/i
Then add a simple check for double hyphens using strpos (if it's false, there is no -- in the string, so we want to return true. Otherwise, we want to return false, so that's why the false === is in there):
false === strpos($string, '--');
So, you could do it as:
function validateAlphaNumericUnderscore($string) {
if (0 < preg_match('/^[a-z0-9][a-z0-9-]*[a-z0-9]$/i', $string)) {
return false === strpos($string, '--');
}
return false;
}
Now, I'm sure there's a way to do it in a single regex (without needing the additional strpos), but I'm blanking on that now. This is a simple regex, and a simple second string comparison (non regex based).
Hopefully this suits your needs...
Edit: In fact, you could make this more efficient by checking for the -- first (since the string function is cheaper than the regex):
function validateAlphaNumericUnderscore($string) {
if (false === strpos($string, '--')
return 0 < preg_match('/^[a-z0-9][a-z0-9-]*[a-z0-9]$/i', $string);
}
return false;
}
ircmaxell's answer uses a regex and a strpos() check, and is an answer I prefer, but here's how I did it with a single regex. Disclaimer: this has vast room for improvement:
function validate_alphanumeric_hyphenated($str)
{
/*
* Match either one or more alphanumeric characters, or a sequence with
* a series of alphanumeric characters without consecutive, leading
* or trailing hyphens.
*
* Is probably unnecessarily long.
*/
return preg_match("/^(?:[a-zA-Z0-9]+|[a-zA-Z0-9](?:[a-zA-Z0-9]|-(?!-))*[a-zA-Z0-9])$/", $str);
}
You could do it with two regexes:
if( !preg_match('/(?:^-|-$|-{2,})/',$str) && preg_match(/^[a-zA-Z0-9_]+$/',$str) ) {
return true;
}