Allow Only [A-Z][A-Z][0-9] in String Using PHP

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);
  1. You did not have the \- in the [] brackets.
    It also seems you can use - instead of \-, both worked for me.

  2. 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



Leave a reply



Submit