-4

How can I build a regex that allows alphanumeric and only one space like :

MM56M pass
MM 54M pass
MMM 5
555555 pass
LPOLKG pass
MM 5T YU does not pass

Thanks

njasi
  • 126
  • 8
oussama kamal
  • 1,027
  • 2
  • 20
  • 44

2 Answers2

1

Would this work:

^[A-Za-z0-9]+( [A-Za-z0-9]+)?$

It matches one or more any-case letters or numbers then possibly a space and one or more any-case letters or numbers

RedLaser
  • 680
  • 1
  • 8
  • 20
0

This regex should work...

/^[[:alnum:]]+( [[:alnum:]]+)?$/

Demo: https://regex101.com/r/hQ6fM4/2 (not the g modifier being used here won't be used in PHP, if the string is multi-lined use the m so the ^$ affect each line).

The [[:alnum:]] is a posix character bracket for an alpha or numerical character. The + after is a quantifier meaning one or more of those characters. The ^$ are anchors the ^ is the start of the string, the $ is the ending. The () is a grouping and the ? after makes that whole second group optional. The / are delimiters telling where the regex starts and ends.

or if you want a strange approach:

$str = 'test test';
$post = preg_replace('/\s/', '', $str);
if (((strlen($str) - 1) == strlen($post) || (strlen($str) == strlen($post))) && ctype_alnum($post)) {
echo  'tis good';
} else {
 echo 'rut row';
}

Demo: https://eval.in/505494

chris85
  • 23,846
  • 7
  • 34
  • 51