在最后一个出现的空格处拆分字符串

12

我需要将一个字符串分成两部分。该字符串包含由空格分隔的单词,并且可以包含任意数量的单词,例如:

$string = "one two three four five";

第一部分需要包含除最后一个单词外的所有单词。

第二部分只需要包含最后一个单词。

编辑:两个部分需要作为字符串返回,而不是数组,例如:

$part1 = "one two three four";

$part2 = "five";


1
strrpos是一个很好的起点。手册上有更多信息。 - GordonM
这不是确切问题的答案,但与标题相关,因为我正在寻找几乎相等的两个部分,并且我通过使用wordwrap实现了这一点。 - hayatbiralem
11个回答

27

有几种方法可以解决这个问题。

数组操作:

$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);

从逻辑上讲,由于 OP 使用字符串而不是数组,我建议使用“非”数组选项,因为它们不需要数组(这使得代码看起来更合乎逻辑,因为它只是在处理一个字符串),但是是否有性能差异呢? - James

9
您需要做的是将输入字符串在最后一个空格处拆分。现在,最后一个空格是不再跟随任何其他空格的空格。因此,您可以使用负向先行断言来查找最后一个空格:
$string="one two three four five";
$pieces = preg_split('/ (?!.* )/',$string);

5

请查看PHP中的explode函数

该函数返回一个字符串数组,其中每个字符串都是由在字符串分隔符上形成的边界拆分字符串而形成的子字符串


3
$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);

3
使用strrpos函数获取最后一个空格字符的位置,然后使用substr函数通过该位置将字符串分割。
<?php
    $string = 'one two three four five';
    $pos = strrpos($string, ' ');
    $first = substr($string, 0, $pos);
    $second = substr($string, $pos + 1);
    var_dump($first, $second);
?>

实时示例


1
$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

1

应该可以这样做:

$arr = explode(' ', $string);
$second = array_pop($arr);
$result[] = implode(' ', $arr);
$result[] = $second;

1

这样做可以解决问题,但并不是特别优雅。

$string=explode(" ", $string);
$new_string_1=$string[0]." ".$string[1]." ".$string[2]." ".$string[3];
$new_string_2=$string[4];

1

我的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";

1
$string="one two three four five";
$matches = array();
preg_match('/(.*?)(\w+)$/', $string, $matches);
print_r($matches);

输出:

数组([0] => 一个 两个 三个 四个 五个 [1] => 一个 两个 三个 四个 [2] => 五个)

那么你需要的部分将是 $matches[1]$matches[2]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接