Mark
Mark

Reputation: 632

preg_match whitespace problem

I need to write a regex but for some reason i cannot get the \s to find whitespace, Im trying....

$name = "a ";

if( preg_match('^[a-z]+\s$', $name)){
  echo "match";
} else {
  echo "no match";
}

ive also tried

preg_match('^[a-z\s]+$');

and

preg_match('^[a-z]/\s/$');

Im just getting no match. The full regex needs to allow 1 or more lowercase letters then a space then an uppercase letter followed by one or more lowercase, but....

preg_match('^[a-z]+\s[A-Z][a-z]+$');

isnt working as i'd expect it to going of the tutorials ive seen around the web (sitepoint etc...).

Anyone shed any light on it?

Upvotes: 0

Views: 2678

Answers (1)

Felix Kling
Felix Kling

Reputation: 816780

You have to add delimiters(docs) to the expressions:

$name = "a ";

if( preg_match('/^[a-z]+\s$/', $name)){
//              ^          ^
//              └----------┴----- here: slash as delimiter
  echo "match";
} else {
  echo "no match";
}

Here I used a slash / but you are pretty much free in choosing a delimiter (ok, not that much: any non-alphanumeric, non-backslash, non-whitespace character).


Make sure you have error reporting set to include warnings, e.g. by adding error_reporting(E_ALL). Then you would have seen this warning:

Warning: preg_match(): No ending delimiter '^' found in ... on line ...
no match

PHP treats the first character in the string as delimiter, so in your case the ^.

Upvotes: 7

Related Questions