Reputation:
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.
Upvotes: 1
Views: 1123
Reputation: 626845
This is the only way to match such words. You have to consume these spaces, otherwise you won't have a match. Actually, your pattern is the same as
t\s*e\s*s\s*t
If the word appears inside a larger string, you can consider a word boundary version:
\bt\s*e\s*s\s*t\b
NOTE: If only one whitespace is allowed in between each letter, you can use ?
quantifier instead of *
:
t\s?e\s?s\s?t
Upvotes: 1
Reputation: 785156
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);
Upvotes: 1