I want to be able to get the remaining string after an explode.

$string = "First Middle Last";
$d = explode(" ", $string);
print_r($d);

Outputs:
$d = array
(
  [0] => First
  [1] => Middle
  [2] => Last
)

$first = $d[0]; // First
$last = $d[1] // Middle

How can I get the last and remaining exploded values?

I want to be able to do:

$last = $d[last?] // Middle Last

I do not want to do

$last = $d[1].$d[2] // Middle Last
有帮助吗?

解决方案

You should probably use the third (optional) argument of explode:

list ($first, $last) = explode(" ", $string, 2);

That said, splitting on spaces is going to work on a lot of human names, but will also fail for quite significant percentage if you take the global view. There's nothing wrong with doing it as a practical solution to a particular problem, just don't expect that it will always work correctly.

其他提示

You could use array_slice. This will indefinitely work for any strings.

<?php
$string = "First Middle Last Next Over";
echo implode(' ',array_slice(explode(" ", $string),1));

OUTPUT :

Middle Last Next Over
$string = "First Middle Last";

preg_match_all("/\s(.*)/", $string , $output_array);

echo $output_array[1][0];

Output // Middle Last

Or simply

preg_match("/\s(.*)/", $string , $output_array);

echo $output_array[1];

Try this.

$string = "First Middle Last";
list($d1,$d2,$d3) = explode(" ", $string);
print_r($d1);
print_r($d2);
print_r($d3);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top