[\W]+ will match any non-word character.

but to match only the characters from the question, use this:

  $string="sadw$"
  if(preg_match("/[\[^\'£$%^&*()}{@:\'#~?><>,;@\|\\\-=\-_+\-¬\`\]]/", $string)){
   //this string contain atleast one of these [^'£$%^&*()}{@:'#~?><>,;@|\-=-_+-¬`] characters
  }
Answer from Trigger Eugene on Stack Overflow
🌐
SitePoint
sitepoint.com › php
Correct rules for escaping special characters in a preg_match() - PHP - SitePoint Forums | Web Development & Design Community
July 3, 2022 - I am trying to learn how to use preg_match() and already I am having problems understanding the logic. At the moment I am exploring searching for special characters using escapes. I have established that the special characters that need escaping are . \ + * ? [ ^ ] $ ( ) { } = ! | : - All good so far as in if (preg_match("/\?/", $string)) {... But if I search for a \ then I need to escape it with a \\as in if (preg_match("/\\\/", $string)) {... Ok, I can accept that as a special case but...
🌐
O'Reilly
oreilly.com › library › view › php-in-a › 0596100671 › ch15s03.html
15.3. Regexp Special Characters - PHP in a Nutshell [Book]
October 13, 2005 - preg_match("/[A-Za-z ]*/", $string); // matches "", "a", "aaaa", "The sun has got his hat on", etc preg_match("/-?[0-9]+/", $string); // matches 1, 100, 324343995, and also -1, -234011, etc. The "-?" means "match exactly 0 or 1 minus symbols" This next regexp shows two character classes, with the first being required and the second optional.
Author: Paul Hudson
Published: 2005
Pages: 372
🌐
SitePoint
sitepoint.com › php
Regex for Special Characters - PHP - SitePoint Forums | Web Development & Design Community
July 5, 2012 - // Check for Special-Character. if (empty($errors)){ if (!preg_match("#[\\~\\`\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\-\\+\\=\\{\\}\\[\\]\\|\\:\\;\\ \\.\\?\\/\\\\\\\\]+#", $newPass1)){ $errors['newPass'] = 'Password must have at least 1 Special Character.'; } } 1.) Someone told me I do NOT need ...
🌐
David Walsh
davidwalsh.name › letters-regex
Match Special Letters with PHP Regular Expressions
August 24, 2017 - preg_match( "/([\pL -]+)?\s?\[?\(?:([\pL0-9\-\_]+)\)?\]?/u", "Yep Nopé [:ynope]", $matches); // 0 => 'Yep Nopé [:ynope]', 1 => 'Yep Nopé', 2 => 'ynope' You can see my simple test bed here. If you're afraid that other characters might seep in, or don't trust \pL, you could list every special letter manually (i.e.
🌐
PHP
php.net › manual › en › function.preg-match.php
PHP: preg_match - Manual
When trying to match accented characters, such as those found in Spanish, there seems to be a different internal interpretation when using character classes. So the best way is to add the u option (for unicode) after the delimiters. <?php //echoes 1 (adding u would not alter the result) echo preg_match('/^áéíóúñ$/', 'áéíóúñ'); //echoes 0 (unless with [ó]+ or [ó]* or adding u) echo preg_match('/^áéí[ó]úñ$/', 'áéíóúñ'); //so to match 'espana' or 'españa', add u or this won't match //echoes 1 echo preg_match('/^espa[nñ]a$/u', 'españa'); ?>
Find elsewhere
🌐
PHPBuilder
board.phpbuilder.com › d › 10377743-resolved-preg-match-search-for-special-chracters
[RESOLVED] Preg_Match - search for special chracters - PHPBuilder Forums
January 17, 2011 - Hi guys, I'm relatively new to PHP and I want to create a preg_match statement that searches for numbers and special characters. Currently I have. preg_ma...
🌐
Stack Overflow
stackoverflow.com › questions › 71054982 › word-with-special-characters-match-via-preg-match-in-php
regex - Word with special characters match via preg_match in php - Stack Overflow
February 9, 2022 - $str ="Model number is FM223-56/89."; $model ="FM223-56/89."; $pattern = '/(?!\B\w)' . preg_quote($model, '/') . '(?<!\w\B)/'; echo preg_match($pattern, $str); // => 1 · See the PHP demo. (?!\B\w) - checks if the next char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required · (?<!\w\B) - checks if the previous char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required. Note the preg_quote($model, '/') part: it escapes all special chars in the $model string and also the / char that is used as a regex delimiter char.
Top answer
1 of 5
1

Use this preg_match code to only allow Letters (including uppercase), Numbers, and Spaces:

$Passed = 0;
$username = $_POST['username'];
$password = $_POST['password'];

if(!preg_match("/[^a-z0-9 ]/i", $username)){
    $Passed = 1;
    //stop header location here.
}
else{
    $message = "Your username may only contain letters, numbers and spaces";
    $_SESSION['error'] = $message;
    header("Location:auth.php");
}
if ($Passed == 0){
    header("Location:index.php");
}
2 of 5
1

About your original question:

This regular expression doesn't work properly due to caret (^) position:

/[^a-zA-Z0-9[:space:]]+$/
  ↑

In this position, caret negate following pattern inside square brackets. In fact, your pattern search for any not a-zA-Z0-9....

To match a string with only alphanumeric characters and spaces you have to move the caret at start of pattern. In this position the caret means “start of string”:

/^[a-zA-Z0-9[:space:]]+$/
 ↑

But you can also simplify your pattern, and replace [:space:] with a real blank space ([:space:] and \s match also newline, tab, etc...1). Try this regular expression:

/^[A-z0-9 ]+$/

Your script still not working:

The solution is die().

If the string doesn't match the pattern, you execute this code:

$message = "Your username may only contain letters, numbers and spaces";
$_SESSION['error'] = $message;
header("Location:auth.php");

Sending headers doesn't interrupt the script, so the remaining code is executed and the last sent header (Location:index.php) is loaded.

Force script termination after sending header:

header("Location:auth.php");
die();

1 From PHP documentation: “The "whitespace" characters are HT (9), LF (10), FF (12), CR (13), and space (32). However, if locale-specific matching is happening, characters with code points in the range 128-255 may also be considered as whitespace characters, for instance, NBSP (A0).”

🌐
Experts Exchange
experts-exchange.com › questions › 27663739 › Need-a-wise-strategy-for-validating-names-with-special-characters-preg-match.html
Solved: Need a wise strategy for validating names with special characters: preg_match() | Experts Exchange
April 5, 2012 - As far as regular expressions go, ... every character you want to keep inside the brackets, and use preg_replace() to remove all the characters you do not want to keep....
🌐
PHP Freaks
forums.phpfreaks.com › php coding › regex help
preg_match Check for Special Characters - Regex Help - PHP Freaks
October 25, 2010 - Hi. I'm trying to create a simple function that checks my text strings (ie. firstname & lastnames ect) for illigal characters. I'm using: trim() strip_tags() as well as preg_match I keep getting an echo of True if if I put in valid values. ie. Joe From my understanding the below statement wil...
🌐
GitHub
gist.github.com › cferdinandi › 6688744
Test strings for letters, numbers, and special characters. Returns true if they exist, false if they don't. Forked from http://stackoverflow.com/a/9588010/1293256 · GitHub
Test strings for letters, numbers, and special characters. Returns true if they exist, false if they don't. Forked from http://stackoverflow.com/a/9588010/1293256 - has-characters.php
🌐
MetaProgrammingGuide
metaprogrammingguide.com › code › preg-match-special-characters
Php, Preg_match special characters
June 7, 2022 - Preg match - PHP preg_match special characters only, You need to match the string for any alphanumeric character.