我需要将一个字符串分成两部分.该字符串包含由空格分隔的单词,可以包含任意数量的单词,例如:
$string = "one two three four five";
第一部分需要包含所有单词,除了最后一个单词.第二部分需要包含最后一个单词.
任何人都可以建议吗?
编辑:这两个部分需要作为字符串返回,而不是数组,例如:
$part1 = "one two three four";
$part2 = "five";
Mar*_*c B 25
几种方式你可以去做.
数组操作:
$string ="one two three four five";
$words = explode(' ', $string);
$last_word = array_pop($words);
$first_chunk = implode(' ', $words);
Run Code Online (Sandbox Code Playgroud)
字符串操作:
$string="one two three four five";
$last_space = strrpos($string, ' ');
$last_word = substr($string, $last_space);
$first_chunk = substr($string, 0, $last_space);
Run Code Online (Sandbox Code Playgroud)
你需要的是在最后一个空格上分割输入字符串.现在最后一个空格是一个空格,后面没有任何空格.因此,您可以使用负前瞻断言来查找最后一个空格:
$string="one two three four five";
$pieces = preg_split('/ (?!.* )/',$string);
Run Code Online (Sandbox Code Playgroud)