Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode string php

Tags:

php

$string = "|1|2|3|4|";
$array = explode("|", $string, -1); 

foreach ($array as $part) {
    echo $part."-";
}

I use -1 in explode to skip the last "|" in string. But how do I do if I also want to skip the first "|"?

like image 620
Daniel Avatar asked Jul 23 '11 07:07

Daniel


2 Answers

You can use trim to Strip | from the beginning and end of a string and then can use the explode.

$string = "|1|2|3|4|";
$array = explode("|", trim($string,'|')); 
like image 187
Shakti Singh Avatar answered Sep 21 '22 08:09

Shakti Singh


preg_split(), and its PREG_SPLIT_NO_EMPTY option, should do just the trick, here.

And great advantage : it'll skip empty parts even in the middle of the string -- and not just at the beginning or end of it.


The following portion of code :

$string = "|1|2|3|4|";
$parts = preg_split('/\|/', $string, -1, PREG_SPLIT_NO_EMPTY);
var_dump($parts);


Will give you this resulting array :

array
  0 => string '1' (length=1)
  1 => string '2' (length=1)
  2 => string '3' (length=1)
  3 => string '4' (length=1)
like image 26
Pascal MARTIN Avatar answered Sep 19 '22 08:09

Pascal MARTIN