What is the difference between the preg_split and the explode?

Asked

Viewed 120 times

2

What is the difference between the functions preg_split and explode? When to use one or the other?
I came across this code and I’m trying to understand its workings.

function consulta_header_grid($campos){
  $linha = preg_split('/[\n]/', $campos, -1, PREG_SPLIT_NO_EMPTY);
  foreach($linha as $linha){
    $colunas = explode("    ", $linha);
    $header[$colunas[0]] = $colunas[0] . ";" . $colunas[1] . ";" . $colunas[2];
  }

  return $header;
}

2 answers

4

The main difference between the explode(); and preg_split(); is that you can use regular expression in preg_split();, however, according to the stack with., the explosion is usually faster (follows the reference).

In short, if it is a more complex filtering use the preg_split();, if it’s something simpler use the explode();.

In his example, he uses the preg_split(); with the "\n" stop breaks at each line, and the explode(""), to generate an array based on the spaces.

  • 1

    Thank you very much, I help me a lot.

0

Both are used to divide one string in a array, the difference is that split() uses the "Pattern", while explode() uses string. explode() is faster than split() because it does not correspond to string based on regular expression.

  • 1

    Vlw brother, now I understand the code

Browser other questions tagged

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