Click here to Skip to main content
11,719,903 members (88,072 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: PHP splitter
Hi all,

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

$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.

$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 19-Jan-13 6:25am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
$str = 'one/two/three/four';
$arr = explode('/', $str, 2);
the result will be
one
two/three/four
and with this
$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:
$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.
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

An alternative without array functions...
$last = strrpos($str, '/');
$left = substr($str, 0, $last);
$right = substr($str, $last+1);
  Permalink  

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 1,869
1 OriginalGriff 770
2 F-ES Sitecore 640
3 Maciej Los 609
4 Richard MacCutchan 540


Advertise | Privacy | Mobile
Web02 | 2.8.150901.1 | Last Updated 19 Jan 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100