我需要将一个字符串分成两部分。该字符串包含由空格分隔的单词,并且可以包含任意数量的单词,例如:
$string = "one two three four five";
第一部分需要包含除最后一个单词外的所有单词。
第二部分只需要包含最后一个单词。
编辑:两个部分需要作为字符串返回,而不是数组,例如:
$part1 = "one two three four";
$part2 = "five";
我需要将一个字符串分成两部分。该字符串包含由空格分隔的单词,并且可以包含任意数量的单词,例如:
$string = "one two three four five";
第一部分需要包含除最后一个单词外的所有单词。
第二部分只需要包含最后一个单词。
编辑:两个部分需要作为字符串返回,而不是数组,例如:
$part1 = "one two three four";
$part2 = "five";
有几种方法可以解决这个问题。
数组操作:
$string ="one two three four five";
$words = explode(' ', $string);
$last_word = array_pop($words);
$first_chunk = implode(' ', $words);
字符串操作:
$string="one two three four five";
$last_space = strrpos($string, ' ');
$last_word = substr($string, $last_space);
$first_chunk = substr($string, 0, $last_space);
$string="one two three four five";
$pieces = preg_split('/ (?!.* )/',$string);
$string="one two three four five";
list($second,$first) = explode(' ',strrev($string),2);
$first = strrev($first);
$second = strrev($second);
var_dump($first);
var_dump($second);
$string = "one two three four five";
$array = explode(" ", $string); // Split string into an array
$lastWord = array_pop($array); // Get the last word
// $array now contains the first four words
应该可以这样做:
$arr = explode(' ', $string);
$second = array_pop($arr);
$result[] = implode(' ', $arr);
$result[] = $second;
这样做可以解决问题,但并不是特别优雅。
$string=explode(" ", $string);
$new_string_1=$string[0]." ".$string[1]." ".$string[2]." ".$string[3];
$new_string_2=$string[4];
我的Perl解决方案 :)... PHP和Perl很相似 :) $string="one five three four five";
@s = split(/\s+/, $string) ;
$s1 = $string ;
$s1 =~ s/$s[-1]$//e ;
$s2 = $s[-1] ;
print "The first part: $s1 \n";
print "The second part: $s2 \n";
$string="one two three four five";
$matches = array();
preg_match('/(.*?)(\w+)$/', $string, $matches);
print_r($matches);
输出:
数组([0] => 一个 两个 三个 四个 五个 [1] => 一个 两个 三个 四个 [2] => 五个)
那么你需要的部分将是 $matches[1]
和 $matches[2]
。