2by
2by

Reputation: 1093

Preg_match validating special chars inside a string

I want to only allow letters, numbers, spaces, unserscore and hyphens.

So far i thought that this preg_match would do the job:

if(preg_match('/[^a-z0-9 _]+$/i', $name)) {
$error = "Name may only contain letters, numbers, spaces, \"_\" and \"-\".";
}

But i just realized that special chars inside a string, would not generate an error. For example

hello"@£$joe

would not generate an error. Is it possible to make a little change and make it work, or do i need another solution?

Upvotes: 2

Views: 19135

Answers (4)

Vipin Jain
Vipin Jain

Reputation: 1402

Here Take this:

/^[a-z0-9\s\-_]+$/i

this expression is tested by me with dummy data.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function valueanalysis(form){
    var vals = form.vals.value;

    alert(/^[a-z0-9\s\-_]+$/i.test(vals));

    return false;
}
</script>
</head>

<body>
<form onsubmit="return valueanalysis(this);">
<input type="text" name="vals"/>
<input type="submit" value="Check" />
</form>
</body>
</html>

use this code in a html file check the validation by filling the value and press enter afterwards to check if true or not.

Note:- regular expressions are same for all languages.

<?php


if(preg_match("/^[a-z0-9\s\-_]+$/i","ASDhello-dasd  asddasd_dsad")){
    echo "true";
}
else{
    echo "false";
}
?>

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272396

The problem is with the $ symbol. You are specifically asking it to match the end of string. The expression /[^a-z0-9 _]+$/i will not match hello"@£$joe because joe matches [a-z0-9 _]+$; so it obviously won't match when you negate the class. Remove the $ symbol and everything will be as expected:

if(preg_match('/[^a-z0-9 _]+/i', $name)) {
// preg_match will return true if it finds 
// a character *other than* a-z, 0-9, space and _
// *anywhere* inside the string
}

Test it in your browser by pasting these lines one by one in the JavaScript console:

/[^a-z0-9 _]+/i.test("@hello");        // true
/[^a-z0-9 _]+/i.test("joe@");          // true
/[^a-z0-9 _]+/i.test("hello\"@£$joe"); // true
/[^a-z0-9 _]+/i.test("hello joe");     // false

Upvotes: 3

Vipin Jain
Vipin Jain

Reputation: 1402

/^([a-z]|[A-Z]|[0-9]| |_|-)+$/

use this regular expression

Upvotes: 0

codaddict
codaddict

Reputation: 455440

You need to bring the ^ outside the character class:

if(preg_match('/^[a-z0-9 _]+$/i', $name)) {

A ^ inside (at the beginning) a character class acts like a character class negator.

Upvotes: 0

Related Questions