4Answers

Explode string php

7.2k Views
  • 13
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 187

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 187
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

Explode string 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 "|"?

php

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)
  • 4
Reply Report