Instead of the greedy (.*)
, I would recommend using something more specific like \w+
to match one or more "word" characters. Since whitespace may be insignificant, separate them with \s+
. Rather than trying to use {2}
, since you expect exactly two separated by whitespace, it is easier to spell each group out literally as \w+
with the whitespace requirement in between.
^!hello\s+(\w+)\s+(\w+)$
If you don't actually need to reuse the arguments, remove the ()
.
^!hello\s+\w+\s+\w+$
$pattern = '/^!hello\s+\w+\s+\w+$/';
echo preg_match($pattern, '!hello foo bar');
// 1
echo preg_match($pattern, '!hello foo bar baz');
// 0
echo preg_match($pattern, '!hello "foo bar" baz');
// 0
// Note a numeric argument matches \w+... If that isn't allowed
// you should use [A-Za-z]+ instead or just [a-z]+ and add the /i flag
echo preg_match($pattern, '!hello 123 baz');
// 1
echo preg_match($pattern, '!hello a$1 baz');
// 0