Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Empty delimiter" Warning when using PHP explode() function

In javascript, var myStringToArray = myString.split(''); is perfectly acceptable.

But in PHP, $My_String_To_Array = explode('', $My_String); throws an error:

Warning: explode() Empty delimiter

The PHP manual (http://php.net/manual/en/function.explode.php) explains:

If delimiter is an empty string (""), explode() will return FALSE.

So what should I be using in contemporary PHP instead of explode('', $My_String)?

So far, the alternatives I can see are:

  • split("", $My_String) - deprecated as of PHP 5.3.0
  • str_split($My_String)
  • preg_split('//', $My_String)

Seven years ago, str_split() would have been the correct alternative to use.

But is str_split() still in contemporary usage or should I only be looking at preg_split() ?

Or should I be looking at something else?

like image 518
Rounin - Glory to UKRAINE Avatar asked Apr 11 '17 13:04

Rounin - Glory to UKRAINE


People also ask

What does explode () do in PHP?

The explode() function breaks a string into an array. Note: The "separator" parameter cannot be an empty string. Note: This function is binary-safe.

What is the difference between explode () and split () functions in PHP?

Both are used to split a string into an array, but the difference is that split() uses pattern for splitting whereas explode() uses string. explode() is faster than split() because it doesn't match string based on regular expression.

How convert string to array in PHP with explode?

1) Convert String to Array using explode()explode() method is one of the built-in function in PHP which can be used to convert string to array. The explode() function splits a string based on the given delimiter. A delimiter acts as a separater and the method splits the string where the delimiter exists.

How Reverse explode PHP?

PHP ImplodeThe implode function essentially does the opposite of the explode function. You can take an array and join it together and make it into one string instead of an array.


Video Answer


2 Answers

If dealing with multi-byte UTF-8 strings you should use:

$array = preg_split('//u', $My_String,-1, PREG_SPLIT_NO_EMPTY);

Otherwise you can just use:

$array = str_split($My_String);

The reason is noted in the manual:

str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string.

Starting from PHP version 7.4 the mbstring equivalent of str_split was added so you can now use:

$array = mb_str_split($my_string);

mb_str_split manual page

like image 168
apokryfos Avatar answered Sep 29 '22 02:09

apokryfos


the first parameter is required.

explode(separator,string,limit)

[separator]: required;
[string]: required;
[limit]: alternative.

An explode function with a void [separator] is meaningless.

That's all.O(∩_∩)O~

like image 38
lifanko lee Avatar answered Sep 29 '22 04:09

lifanko lee