Allow only [a-z][A-Z][0-9] in string using PHP
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 ]
PHP Replace string allow only a-z A-Z 0-9 _ and . (dot)
if (preg_match('/^[\w\.]+$/', $username)) {
echo 'Username is valid';
}
\w - matches [a-zA-Z0-9_]+
How to use preg_match to only allow strings containing alphabetic and numeric characters?
preg_match('/^[0-9A-Z]*([0-9][A-Z]|[A-Z][0-9])[0-9A-Z]*$/', $subject);
If you want to allow small and capital letters, add an i
at the end of the pattern string.
Explanation:
[0-9][A-Z]
matches one digit followed by one capital letter
[A-Z][0-9]
matches one capital letter followed by one digit
([0-9][A-Z]|[A-Z][0-9])
matches one of these two sequences
[0-9A-Z]*
matches 0-n digits and/or capital letters
The idea is: A string which contains both (and only), letters and numbers, has at least one subsequence where a letter follows a digit or a digit follows a letter. All the other characters (preceding and following) have to be digits or letters.
PHP function to keep only a-z 0-9 and replace spaces with - (including regular expression)
$s = strtolower($s);
$s = str_replace(' ', '-', $s);
$s = preg_replace("/[^a-z0-9\-]+/", "", $s);
You did not have the \- in the [] brackets.
It also seems you can use - instead of \-, both worked for me.You need to add multiplier of the searched characters.
In this case, I used +.
The plus sign indicates one or more occurrences of the preceding element.
Related Topics
Convert an Associative Array to a Simple Array of Its Values in PHP
What's the Difference Between $_Post, $_Get, and $_Request
MySQL Retrieve Variable from Stored Procedure in PHP Pdo
How to Read a Single File Inside a Zip Archive
Remove Index.PHP in Codeigniter 2.1.0
Does PHP Execution Stop After a User Leaves the Page
PHP 7.4 Deprecated Get_Magic_Quotes_Gpc Function Alternative
How to Kill A/All PHP Sessions
Binding Params for Pdo Statement Inside a Loop
PHP Code to Test Pdo Is Available
How to Replace a Function in PHP (Such as Mail) and Make It Do Something Else
Having Problems While Try to Install Oauth with Pecl in Mamp on MAC Os Lion