问题
I'd like to have a regex to match a word, even if there are spaces between the characters.
When I want to match the word test
, it should match the following:
test
t est
t e s t
And so on, but it should not match things like this:
tste
te ts
s tet
I have this regex:
(t[\s]*e[\s]*s[\s]*t[\s]*)
But I don't believe that this one is very efficient.
回答1:
Actually, it is the same as t\s*e\s*s\s*t
(if the word appears inside a larger string, \bt\s*e\s*s\s*t\b
is preferable). This is the only way to match such words. You have to consume these spaces, otherwise you won't have a match.
回答2:
Why not remove all horizontal spaces from input and then match regex:
$input = 't e s t';
$regex = '/\btest\b/i';
preg_match($regex, preg_replace('/\h+/', '', $input), $m);
来源:https://stackoverflow.com/questions/29363421/regex-to-match-a-word-even-is-there-are-spaces-between-letters