问题
Is it possible to have php explode work on an exact word? For example, I wish to split the string:
London Luton to Paris
However, php explode will find the first occurrence of 'to' which is in 'Luton'. This string is also possible:
Paris to London Luton
Which will correctly explode as the 'to' appears first.
Ideally, I wish for the explode to be case insensitive which I believe explode currently is. I figure however that RegEx is probably a better way to go here.
回答1:
simple solution with preg_split
:
$words = preg_split("/\bto\b/iu", "London Luton to Paris");
var_dump($words);
// the output:
array (size=2)
0 => string 'London Luton ' (length=13)
1 => string ' Paris' (length=6)
回答2:
If you want to explode using 'to'
as separator then you can use the string ' to '
instead (it's to
with one space on each side). This way only when to
is a complete word it is treated as a separator, the to
combination of letters from a larger word does not match.
However, if you need it to be case insensitive, a regex
could be a better solution.
preg_split('/\bto\b/i', 'London Luton to Paris');
splits the string using to
as the separator but only if it is a complete word (the \b
that surround it match only word boundaries).
The i
modifier tells the regex
engine to ignore the case.
The spaces right near the to
separator will be returned in the pieces you get. You can either trim()
all the resulted strings
array_map('trim', preg_split('/\bto\b/i', 'Paris to London Luton');
or you can add them to the regex
:
preg_split('/\s*\bto\b\s*/i', 'Paris to London Luton');
The \s*
part matches a space character (\s
) zero or more times (*
). This way the word to
is identified as a delimiter even if it appears as the first or the last word in the string, together with the spaces that surround it.
来源:https://stackoverflow.com/questions/35138829/php-explode-on-an-exact-word