Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Special Characters Test

What's an efficient way of checking if a username contains a number of special characters that I define.

Examples: % # ^ . ! @ & ( ) + / " ? ` ~ < > { } [ ] | = - ;

I need to detect them and return a boolean, not just strip them out.

Probably a super easy question but I need a better way of doing this than a huge list of conditionals or a sloppy loop.

like image 580
pws5068 Avatar asked Apr 16 '10 01:04

pws5068


People also ask

How do you check if a string contains a special character in PHP?

php function check_string($my_string){ $regex = preg_match('[@_! #$%^&*()<>?/|}{~:]', $my_string); if($regex) print("String has been accepted"); else print("String has not been accepted"); } $my_string = 'This_is_$_sample!

How do I escape a character in PHP?

You can achieve the same effect in double-quoted strings by using the escape character, which, in PHP, is a backslash \.

How remove all special characters from a string in PHP?

Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).


1 Answers

The better is to determine if there are any chars that are not in an allowed list, like:

preg_match('![^a-z0-9]!i', $nickname);
like image 96
zerkms Avatar answered Oct 18 '22 16:10

zerkms