PHP regular expression for alphanumeric and hypen input - php

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

Related

PHP - Find an integer that is 8 digit long in a string between a range of numbers using preg_replace

I am trying to find an integer in a string that has the following characteristics:
- Is exactly 8 digits long
- Is between 21000000 and 22000000
- Or between 79000000 and 79999999
I want any number between those ranges to be redacted.
I tried using preg_replace. I'm not sure which pattern to use for this function.
I would suggest this:
preg_replace('/(^|[^0-9]{1})(21[0-9]{6}|22000000|79[0-9]{6})([^0-9]{1}|$)/', '$1 |$2| $3', $str);
// (^|[^0-9]{1}) - set bordering character as non-numeric
// (21[0-9]{6}|22000000|79[0-9]{6}) - match the numbers range you need
// ([^0-9]{1}|$) make sure it doesn't include any other numbers
NB! Make sure you include $1 and $3 in your replace string, otherwise you'll lose chars surrounding the number.
try
<?php
$str ="sdsds21000021dsds";
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
if($int){
$number_of_digits = strlen((string)$int);
if($number_of_digits == 8){
if((($int >= 21000000)&&($int <=22000000))||(($int >= 79000000)&&($int <=79999999))){
echo $int;
} else { // not found }
} else { // not found }
} else { // not found }
hope it helps :)
I've managed to build a regular expression based on what you need.
Hope it helps!
\b21[0-9]{6}\b|\b79[0-9]{6}\b
\b is word boundary
{number} is repetition count
21 is interpreted literally, as 79 is
[0-9] matches exactly one number in 0-9 range
test it here please if you need to tweak it.
https://regex101.com/

PHP uppercase letter in String

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.

php expressions preg_match

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

How to validiate for a solely alphabetic string with spaces in PHP?

I know that there is the function ctype_alpha, though this one will return FALSE when the string contains spaces (white space character).
How do I allow alpha characters and spaces, but nothing else?
$is_alpha_space = ctype_alpha(str_replace(' ', '', $input)));
or
$is_alpha_space = preg_match('/^[a-z\s]*$/i', $input);
if (preg_match("^/[a-zA-Z ]+$/", $input)) {
// input matches
}
Demo: http://ideone.com/jp6Wi
Docs: http://php.net/manual/en/function.preg-match.php
ctype_alpha(preg_replace('/\s/', '', $mystring))
The inner expression returns the string without spaces, and then you use ctype_alpha`` as you wish
Removing the spaces is the way to go, but remember ctype_alpha results in a false on an empty string these days! Below the method I use...
function validateAlpha($valueToValidate, $spaceAllowed = false) {
if ($spaceAllowed) {
$valueToValidate = str_replace(' ', '', $valueToValidate);
}
if (strlen($valueToValidate) == 0) {
return true;
}
return ctype_alpha($valueToValidate);
}
I would work around with a Simple regex and with the php function preg_match() like this:
if(preg_match("/^[a-zA-Z ]+$/", $varToCheck)){
//your code here
}
The important part here is the regex that identifies the parts you want, in my case I wanted text for a name field and with spaces like the case in here.[a-z] is the range from a to z, A-Z are the range from A to Z and the " " at the end represents the spaces.
Hope this helps someone.

How preg_match works exactly?

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

Categories