Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php validate string with preg_match

I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.

I tried to search on google but I could not find anything usefull.

Can anybody help?

Thank you !

like image 660
NVG Avatar asked Dec 27 '12 15:12

NVG


People also ask

How do you check if a string matches a regex in PHP?

In PHP, you can use the preg_match() function to test whether a regular expression matches a specific string. Note that this function stops after the first match, so this is best suited for testing a regular expression more than extracting data.

What is the return value of Preg_match () function?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What does Preg_match mean in PHP?

Definition and Usage The preg_match() function returns whether a match was found in a string.

Which of the following call to Preg_match will return true?

The preg_match() function returns true if pattern matches otherwise, it returns false.


1 Answers

Use the pattern '/^[A-Za-z0-9_-]*$/', if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'

So:

$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
    #your string is good
}

Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.

like image 191
DWright Avatar answered Oct 11 '22 11:10

DWright