I can split a string with a comma using preg_split
, like
$words = preg_split(\'/[,]/\', $string);
How can I use a dot, a space and
$words = preg_split('/[,\.\s;]/', $string);
something like this?
<?php
$string = "blsdk.bldf,las;kbdl aksm,alskbdklasd";
$words = preg_split('/[,\ \.;]/', $string);
print_r( $words );
result:
Array
(
[0] => blsdk
[1] => bldf
[2] => las
[3] => kbdl
[4] => aksm
[5] => alskbdklasd
)
Try this:
<?php
$string = "foo bar baz; boo, bat";
$words = preg_split('/[,.\s;]+/', $string);
var_dump($words);
// -> ["foo", "bar", "baz", "boo", "bat"]
The Pattern explained
[]
is a character class, a character class consists of multiple characters and matches to one of the characters which are inside the class
.
matches the .
Character, this does not need to be escaped inside character classes. Though this needs to be escaped when not in a character class, because .
means "match any character".
\s
matches whitespace
;
to split on the semicolon, this needs not to be escaped, because it has not special meaning.
The +
at the end ensures that spaces after the split characters do not show up as matches
$words = preg_split('/[\,\.\ ]/', $string);
The examples are there, not literally perhaps, but a split with multiple options for delimiter
$words = preg_split('/[ ;.,]/', $string);
just add these chars to your expression
$words = preg_split('/[;,. ]/', $string);
EDIT: thanks to Igoris Azanovas, escaping dot in character class is not needed ;)