Bagzli
Bagzli

Reputation: 6569

PHP Regex check if contains one or more specified characters

I am trying to check if my string contains one of the following characters: !@#$&* However, whenever I run the test, it always returns false. I am not very versed in Regex and I've been looking at numerous examples and they all seem to point that this is correct, however I guess it is not since it is failing. Can somebody tell me what would be the correct check?

if(!preg_match("#[!@#$&*]+#", $value)){
    return "Character not found";
}
else{
    return "Character found!";
}

Test string is JohnDoe1@

Upvotes: 1

Views: 184

Answers (2)

Scuzzy
Scuzzy

Reputation: 12322

Replace "#[!@#$&*]+#" with "#[!@\#\$&*]+#"

Your # delimiter is conflicting and as a secondary your $ might be parsed as a variable because you've got double quotes.

Other option includes single quotes and a different delimter '/[!@#$&*]+/'

Upvotes: 1

user557597
user557597

Reputation:

Its failing because you are using the delimiter inside the regex without
escaping it.

Try a different delimiter

"~[!@#$&*]+~" 

or escape the delimiter

"#[!@\#$&*]+#"

Upvotes: 1

Related Questions