1

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 a semicolon to split string with any of these?

PS. I couldn't find any relevant example on the PHP preg_split page, that's why I am asking.

6 Answers 6

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

@chh: The dot (.) is just a dot inside a character class and doesn't need to be escaped.
Oh, thanks. I guess, escaping regex special characters is kind of a habit :-)
3

The examples are there, not literally perhaps, but a split with multiple options for delimiter

$words = preg_split('/[ ;.,]/', $string);

Comments

2

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
)

2 Comments

but, if there is no dot(.), semi-colon(;), space or comma(,), then how to it should it done.
Open another question with your specific question. This question specifically asked about dot, semicolon, space, or comma.
1
$words = preg_split('/[\,\.\ ]/', $string);

1 Comment

Too \mu\ch u\necce\ss\ary \e\s\c\a\p\i\n\g \i\n thi\s \ans\wer.
1

just add these chars to your expression

$words = preg_split('/[;,. ]/', $string);

EDIT: thanks to Igoris Azanovas, escaping dot in character class is not needed ;)

1 Comment

No need to escape . inside brackets
0
$words = preg_split('/[,\.\s;]/', $string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.