1

How can I alter the pattern below to allow 1 space character ?

$name = 'too long name';
$pattern_name = '/[^a-zA-Z]/';
if (preg_match($pattern_name,$name)) { // remove any non-letter characters
  $name = preg_replace($pattern_name,'',$name);
  $errors['name'] = 'Invalid characters found and removed in name';
}

Using either of these patterns does not work:

$pattern_name = '/[^a-zA-Z ?]/';  
$pattern_name = '/[^a-zA-Z] ?/';

Expected result is a match, since 2 space characters exists in $name, thus the if-statement should be true and the replace function will update $name so its value will become "too longname".

Kim
  • 2,747
  • 7
  • 41
  • 50

3 Answers3

3

You'll have to make your pattern more explicit. If you can have one space at maximum, and it must be surrounded by letters, then:

$pattern_name = '/^[a-z]+( [a-z]+)?$/i';
mario
  • 144,265
  • 20
  • 237
  • 291
  • This matches everything after the first space, which is not desirable as the following replace function will remove too much. Maybe I need to have 2 patterns, where the first removes all other spaces but the first. The second pattern will then remain as the original posted. – Kim Apr 03 '11 at 18:03
  • Yes, that seems the issue here. You cannot use the same regex for both matching and filtering. You will need `/^[\w ]+$/` for the preg_match, and `preg_replace('/^([a-z]+( [a-z]+)?).*?$/s','\1', $name)` for the filtering. – mario Apr 03 '11 at 18:12
0

It should be as simple as adding a space in the brackets.

$pattern_name = '/[^a-zA-Z ]/';
Flipper
  • 2,589
  • 3
  • 24
  • 32
0

I'd invert the regex, and instead of trying to find invalid characters, match valid names (is that what you are doing?). That gives us this regex: /[a-zA-Z]+ [a-zA-Z]+/. Match valid characters, one space and then more valid characters.

Håvard
  • 9,900
  • 1
  • 41
  • 46