9
$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 "|"?

0

4 Answers 4

11

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,'|')); 
Sign up to request clarification or add additional context in comments.

Comments

4

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)

Comments

0

take a substring first, then explode. http://codepad.org/4CLZqkle

<?php

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

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

/* or use implode to join */
echo implode("-",$array);

?>

Comments

0

You could use array_shift() to remove the first element from the array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.