1

I have a string that looks something like this:

abc-def-ghi-jkl-mno-pqr-stu-vwx-yz I'd like to get the content BEFORE the 4th dash, so effectively, I'd like to get abc-def-ghi-jkl assigned to a new string, then I'd like to get mno assigned to a different string.

How could I go about doing this? I tried using explode but that changed it to an array and I didn't want to do it that way.

4 Answers4

7

Try this:

$n = 4; //nth dash
$str = 'abc-def-ghi-jkl-mno-pqr-stu-vwx-yz';  

$pieces = explode('-', $str);
$part1 = implode('-', array_slice($pieces, 0, $n));
$part2 = $pieces[$n];

echo $part1; //abc-def-ghi-jkl
echo $part2; //mno

See demo


http://php.net/manual/en/function.array-slice.php

http://php.net/manual/en/function.explode.php

http://php.net/manual/en/function.implode.php

Mark Miller
  • 7,442
  • 2
  • 16
  • 22
0

Can you add your source code? I done this one before but I cant remember the exact source code I used. But I am pretty sure I used explode and you can't avoid using array.

EDIT: Mark M answer is right.

MarkP.
  • 11
  • 9
0

you could try using substr as another possible solution

http://php.net/manual/en/function.substr.php

If I see where you are trying to get with this you could also go onto substr_replace

hounded
  • 666
  • 10
  • 21
0

I guess an alternative to explode would be to find the position of the 4th - in the string and then get a substring from the start of the string up to that character.

You can find the position using a loop with the method explained at find the second occurrence of a char in a string php and then use substr(string,0,pos) to get the substring.

$string = "abc-def-ghi-jkl-mno-pqr-stu-vwx-yz";
$pos = -1;
for($i=0;$i<4;$i++)
     $pos = strpos($string, '-', $pos+1);
echo substr($string, 0, $pos);

Code isn't tested but the process is easy to understand. You start at the first character (0), find a - and on the next loop you start at that position +1. The loop repeats it for a set number of times and then you get the substring from the start to that last - you found.

Community
  • 1
  • 1
GoLoT
  • 26
  • 3