Domanda

The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message:

$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed"; 
}

My question is how I can add dot (.) in here ?

È stato utile?

Soluzione

Exchange this line:

if (!preg_match("/^[a-zA-Z ]*$/",$name))

with this line:

if (!preg_match("/^[a-zA-Z\. ]*$/", $name))

You have to escape the . character, as it has special meaning in regular expressions.

Altri suggerimenti

$pattern = "/^[a-zA-Z \.]*$/";

You can always add a . in the square brackets. For example the expression [a-zA-Z.] is correct and will give you the thing you want i.e. a list of characters to be checked. If you want to check for . outside the [] then escape the . like . Also your code does not check for tabs which is whitespace. So you should add \s instead of ' '. Similarly there are a lot of other special characters such as ? which will be considered normal characters in the [] brackets. One exception is the - which has to be always added at the end i.e. [A-Z?-]. There are however still some special characters that have to escaped such as "'/. My advice is run the expression online to check first before inserting it into your code. Regex errors are very common and very difficult to find. Your expression should be :-

 $name = test_input($_POST["name"]);
 if (!preg_match("/^[a-zA-Z.\s]+$/",$name)) {
 $nameErr = "Only letters and white space allowed"; 
 }

Cheers!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top