php regex for checking a string - php

I need a regular expression for checking a string, that it has more than 2 symbols length, first symbol should be Alphabetic, last symbol should be '_'.
And how can I uppercase only first symbol?
Thank you.

To match
preg_match( "/^[a-z].+_$/i", $str );
To uppercase the first letter
ucfirst( $str );

To match an input with at least 3 char with first being uppercase alphabet and last begin underscore use:
^[A-Z].+_$
To allow any alphabet in the beginning you can use:
^[A-Za-z].+_$

Try this :
/^[a-zA-Z].+_$/
Note:
instead of .+ you could use [some allowed chars]+

You could also do it like this (might save further regular expression dithering down the line):
if ((strlen($str) < 3) || !ctype_alpha($str[0]) || (strrchr($str, '_') != '_')) {
echo 'Invalid string';
} else {
$str = ucfirst($str);
}

Related

How can I check whether is a string contains only English letters?

I use PHP and I need to check whether is a string made of just
English Lowercase letter
dash
underline?
Something like this:
if ( /* the condition */ ) {
// Yes, all characters of the string are English lowercase letters or dash or underline
} else {
// No, there is at least one unexpected character
}
Here is some examples:
$str = "test"; // true
$str = "test_-'; // true
$str = "t-s"; // true
$str = "test1"; // false
$str = "Test"; // false
$str = "test?"; // false
To match a whole string that only consists of 1 or more lowercase ASCII letters, hyphen or underscores, use
/^[-a-z_]+$/D
See the regex demo
Details:
^ - start of string
[-a-z_]+ - 1 or more ASCII lowercase letters, hyphens or underscores
$ - end of string
/D - the modifier that will make $ match the very end of the string (otherwise, $ will also match a newline that appears at the end of the string).
PHP:
if (preg_match('/^[-a-z_]+$/D', $input)) {
// Yes, all characters of the string are English lowercase letters or dash or underline
} else {
// No, there is at least one unexpected character
}
Use the PHP function
preg_match()
with this regular expression:
$regex = [a-z\_\-]+
The \ are to escape out the underscore and dash. + means you have to have at least 1 character.
This is a handy tool for regular expressions http://www.regexpal.com/
Try this on for size
/**
* Test if a string matches our criteria
*/
function stringTestOk($str) {
return !(preg_match_all('/[^a-z_\-]/', $str) > 0);
}
// Examples
foreach(['test', 'test_-', 't-s', 'test1', 'Test', 'test?'] as $str) {
echo $str, ' ', (stringTestOk($str) ? 'true' : 'false'), PHP_EOL;
}

Regular expression with alpha numeric and need to check length of the string

I have a regular expression which compares if a string is having both alpha and numerical values. But i need to compare if the string is having any special characters and length of the string should be 6.
my current regular expression is
$val = 'A457718';
preg_match('/^[A-Z]|[0-9A-Z]*([0-9][A-Z]|[A-Z][0-9])[0-9A-Z]*$/i', $val)
But i need to compare if there are any special characters are there and string length should be 6. Any help would be greatly appreciated.
You don't need a regex to check for string that is 6 characters long and only numerical.
$val = 'A457718';
if (is_numeric($val) && strlen($val) == 6) {
echo 'true';
} else {
echo 'false';
}
Demo: http://sandbox.onlinephpfunctions.com/code/25c426d1bbbfce4a96c8c1ba74cc4a84b66c2435
Functions:http://php.net/manual/en/function.is-numeric.phphttp://php.net/manual/en/function.strlen.php
If for some reason you require it in regex.
preg_match('~^\d{6}$~', $val);
Demo: https://regex101.com/r/oR9bT4/1
The pattern /^[a-zA-Z0-9]{6}$/ will match six characters that are alphanumeric.
if(preg_match('/^[a-zA-Z0-9]{6}$/', 'A45BBB')){
// Is valid
}
for the length, put at the end {0,6} .. this will limit string to be from 0 to 6 characters
This would match any 6-length alphanumeric string:
\b[a-zA-Z0-9]{6}\b
or including the underscore character:
\b\w{6}\b
This should be clarified:
But i need to compare if there are any special characters

PHP Check For One Letter and One Digit

How can I check if a string is at least one letter and one digit in PHP? Can have special characters, but basically needs to have one letter and one digit.
Examples:
$string = 'abcd' //Return false
$string = 'a3bq' //Return true
$string = 'abc#' //Return false
$string = 'a4#e' //Return true
Thanks.
Try this
if (preg_match('/[A-Za-z]/', $string) & preg_match('/\d/', $string) == 1) {
// string contains at least one letter and one number
}
preg_match('/\pL/', $string) && preg_match('/\p{Nd}/', $string)
or
preg_match('/\pL.*\p{Nd}|\p{Nd}.*\pL/', $string)
or
preg_match('/^(?=.*\pL)(?=.*\p{Nd})/', $string)
or
preg_match('/^(?=.*\pL).*\p{Nd}/', $string)
I'm not sure if \d is equivalent to [0-9] or if it matches decimal digits in PHP, so I didn't use it. Use whichever of \d, [0-9] and \p{Nd} that matches that right thing.
The pattern you're looking for is ^.*(?=.*\d)(?=.*[a-zA-Z]).*$
In use:
if( preg_match( "/.*(?=.*\d)(?=.*[a-zA-Z]).*/", $string ) )
echo( "Valid" );
else
echo( "Invalid." );
That should work if latin chars only and numbers:
if (preg_match('/[a-z0-9]+/i', $search_string)) { ... has at least one a-zA-Z0-9 ... }

PHP right search pattern of a char within a fixed length alpha-numerical string

I did a search but I didn't found anything . I'm looking for a pattern that will search in an alpha-numeric string (with the exact length of 7) the letter "P" . This is what I came up with until now , why isn't working ?
$pattern = "/^[\wP]{7}$/";
Well it isn't working because [\wP]{7} (in your regex: /^[\wP]{7}$?/) means find 7 characters that are either a word character OR the letter P. It could find all Ps and it would match, or all word characters and it would match. My quick fix would be to verify the string is 7 letters long using a regex then do a string position to find the "P":
if(preg_match("/^[\w]{7}$/", $target) && strpos($target, "P") != -1) {
// Do stuff
}
Try this:
$pattern = '/^([a-zA-Z0-9]{6})(P{1})$/';
You could condider using strpos and strlen for speed!
\w contains a-z, A-Z, 0-9 and _ so it is not what you want at all.
I'll try with:
if ( preg_match("/^[a-z0-9]*P[a-z0-9]*$/i", $target) && ( strlen($target) == 7 ) ) { ... }
This should match any string that is 7 characters long and contains an uppercase P:
(?=^\w{7}$)\w*P\w*

Allow only [a-z][A-Z][0-9] in string using PHP

How can I get a string that only contains a to z, A to Z, 0 to 9 and some symbols?
You can filter it like:
$text = preg_replace("/[^a-zA-Z0-9]+/", "", $text);
As for some symbols, you should be more specific
You can test your string (let $str) using preg_match:
if(preg_match("/^[a-zA-Z0-9]+$/", $str) == 1) {
// string only contain the a to z , A to Z, 0 to 9
}
If you need more symbols you can add them before ]
Don't need regex, you can use the Ctype functions:
ctype_alnum: Check for alphanumeric character(s)
ctype_alpha: Check for alphabetic character(s)
ctype_cntrl: Check for control character(s)
ctype_digit: Check for numeric character(s)
ctype_graph: Check for any printable character(s) except space
ctype_lower: Check for lowercase character(s)
ctype_print: Check for printable character(s)
ctype_punct: Check for any printable character which is not whitespace or an alphanumeric character
ctype_space: Check for whitespace character(s)
ctype_upper: Check for uppercase character(s)
ctype_xdigit: Check for character(s) representing a hexadecimal digit
In your case use ctype_alnum, example:
if (ctype_alnum($str)) {
//...
}
Example:
<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo 'The string ', $testcase, ' consists of all letters or digits.';
} else {
echo 'The string ', $testcase, ' don\'t consists of all letters or digits.';
}
}
Online example: https://ideone.com/BYN2Gn
Both these regexes should do it:
$str = preg_replace('~[^a-z0-9]+~i', '', $str);
Or:
$str = preg_replace('~[^a-zA-Z0-9]+~', '', $str);
A shortcut will be as below also:
if (preg_match('/^[\w\.]+$/', $str)) {
echo 'Str is valid and allowed';
} else
echo 'Str is invalid';
Here:
// string only contain the a to z , A to Z, 0 to 9 and _ (underscore)
\w - matches [a-zA-Z0-9_]+
Hope it helps!
If you need to preserve spaces in your string do this
$text = preg_replace("/[^a-zA-Z0-9 ]+/", "", $text);
Please note the way I have added space between 9 and the closing bracket. For example
$name = "!#$John Doe";
echo preg_replace("/[^a-zA-Z0-9 ]+/", "", $name);
the output will be:
John Doe
Spaces in the string will be preserved.
If you fail to include the space between 9 and the closing bracket the output will be:
JohnDoe
Hope it helps someone.
The best and most flexible way to accomplish that is using regular expressions.
But I`m not sure how to do that in PHP but this article can help. link

Categories