Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

In PHP I just want to split a string, from a delimiter.

PHP
$str = "one/two/three";

$arr = explode('/', $str);


I just want to split this int to maximum arrays of two. So I can do it as follows.

PHP
$str = "one/two/three";

$arr = explode('/', $str, 2);


So the output will be,

one
two/three

But, I want to split it as,

one/two
three

How can I do that?
Posted

I think you misunderstand the limit parameter off the explode[^] function. It is used to limit the number off element to be returned by the explode function and all remaining part are stored in the last string.

If you had used this
PHP
$str = 'one/two/three/four';
$arr = explode('/', $str, 2);

the result will be
one
two/three/four
and with this
PHP
$str = 'one/two/three/four';
$arr = explode('/', $str, 3);

the result will be
one
two
three/four


I found this How to Explode String Right to Left?[^] and based on it you can use:
PHP
$str = 'one/two/three';
$arr = array_map('strrev', explode('/', strrev($str), 2));

I have not tested it, so you need to see if it works.
 
Share this answer
 
v2
An alternative without array functions...
PHP
$last = strrpos($str, '/');
$left = substr($str, 0, $last);
$right = substr($str, $last+1);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900