phparrayssplitlimit

Split a string on all delimiters except the last one


I have this right now:

$s = preg_split('/\s+/', $q);
    $k = end($s);

What I want now is to get all the values in the array $k[] except the last one, and join them in a new string. So basically if the array was :

0 => Hello
1 => World
2 => text

I would get Hello World.


Solution

  • Use array_slice and implode:

    $k = array( "Hello", "World", "text" );
    $sliced = array_slice($k, 0, -1); // array ( "Hello", "World" )
    $string = implode(" ", $sliced);  // "Hello World";