1

I would like to split a string by an array of characters, how would I do that? I notice preg_split takes a string input not an array.

For example, here is my array:

$splitting_strings = array(".", ";", "-", "and", "for");

$text = "What a great day, and I love it. Who knows; maybe I will go.";

$result = array (
0 => "What a great day",
1 => "I love it",
2 =>  "Who knows",
3 => "maybe I will go");

1 Answer 1

2

You can pass preg_split() the following:

$regex = '/(' . implode('|', $splitting_strings) . ')/';

You will need to escape any special regex characters such as .. So you should end up with something like this instead:

// run through each element in the array escaping any
// special regex chars
$splitting_strings = array_map(function($string) {
                                   return preg_quote($string);
                               }, $splitting_strings);

$regex = '/(' . implode('|', $splitting_strings) . ')/';
$final_array = preg_split($regex, $splitting_strings);

The output of $final_array after all this is:

array(5) {
  [0]=>
  string(18) "What a great day, "
  [1]=>
  string(10) " I love it"
  [2]=>
  string(10) " Who knows"
  [3]=>
  string(16) " maybe I will go"
  [4]=>
  string(0) ""
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, it should be round brackets no? [and] also matches "dna", since square brackets are for character classes, while round brackets are for grouping as I understand.
Yes it should be () instead of []
I have updated this, but it means you will now need to escape regex symbols such as . to stop it from splitting on everything! :)
@giorgio79 I had updated the answer with a simple a escaping routine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.