What makes it explode() better than split() in php?

Asked

Viewed 2,641 times

3

I know the function split is obsolete and there is the function explode which replaces it, but what exactly causes the explode be better?

  • 1

    Explode does not replace(u) a split, because the two are completely different in terms of operation. The function explodes is limited to dividing string for string, or even when specified a term, it works from there, while the function split uses(va) as the basis regular expressions to break down the strings. Still the differences are quite obvious and explicit in the php, and also because I do not know whether an answer to this question already exists, I will leave only this comment.

1 answer

5


Split is a function of older versions of PHP, which did something similar to explode, differing in the use of regular expressions.

I don’t remember the reference now, but that function was six times slower than explode.

Now, we have to take into account that both are similar, not identical. Explode works with division through delimiter indicated by string, already split, regular expression.

It is worth remembering that explode did not replace the function split, and yes the function preg_split.

The use of preg_split is encouraged in place of split

Take an example:

$parts = preg_split('/,|\./', 'teste.teste,teste');

This generates:

['test, test, test, test, test']

And by directly answering the question What explodes makes it better than split?

Not using regular expression can mean a lot. Not always when we need to split a string to a array we need a regular expression. Hence the idea of using explode instead of split.

And even though preg_split is the substitute for split, in cases where the string is not parsed strictly for splitting, it is encouraged to use explode instead.

  • Another interesting point is that I thought the function join exists in PHP (I have the impression they wanted to imitate javascript). However, this is synonym for implode. Every PHP function that is synonymous should not be used, because they will be removed in the future.

  • 1

    Note: The Regex /,|./ has the right intention but this wrong, the "." represents anything, so the preg_split will explode the string erroneously, change to /,|\./ or /[,\.]/, because "." is the literal.

  • 1

    Thank you Mr @Guilhermelautert

Browser other questions tagged

You are not signed in. Login or sign up in order to post.