将字符串拆分为两部分

时间:2012-03-27 14:41:59

标签: php

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

$string = "one two three four five";

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

有人可以提供建议吗?

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

$part1 = "one two three four";

$part2 = "five";

12 个答案:

答案 0 :(得分:23)

你可以采取各种方式。

数组操作:

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

答案 1 :(得分:8)

您需要的是在最后一个空格上分割输入字符串。现在最后一个空格是一个空格,后面没有任何空格。因此,您可以使用负前瞻断言来查找最后一个空格:

$string="one two three four five";
$pieces = preg_split('/ (?!.* )/',$string);

答案 2 :(得分:5)

查看PHP中的explode函数

  

返回一个字符串数组,每个字符串都是字符串的子字符串,通过在字符串分隔符形成的边界上将其拆分而形成

答案 3 :(得分:2)

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

答案 4 :(得分: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

答案 5 :(得分:1)

这应该这样做:

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

答案 6 :(得分:1)

使用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);
?>

Live example

答案 7 :(得分:1)

这样的事情可以做到,虽然它不是特别优雅。

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

答案 8 :(得分:1)

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

输出:

Array ( [0] => one two three four five [1] => one two three four [2] => five )

然后您的部分将是$matches[1]$matches[2]

答案 9 :(得分:1)

我在Perl中的解决方案:))PHP和Perl类似:)     $ string =“一五三四五”;

@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";

答案 10 :(得分:0)

贪婪地遍历输入字符串中的字符,然后匹配最新出现的空间并在其上进行拆分。超级简单,没有环顾或捕获或任何其他原因会降低正则表达式引擎的速度。

\K 表示“忘记到目前为止所有匹配的字符”。

代码:(Demo)

$string = "one two three four five";
var_export(
    preg_split('/.*\K /', $string)
);

输出:

array (
  0 => 'one two three four',
  1 => 'five',
)

或者作为单独的变量:(Demo)

[$part1, $part2] = preg_split('/.*\K /', $string);
var_export($part1);
echo "\n";
var_export($part2);

答案 11 :(得分:-1)

这可能会帮助您:

$part1 = "one two three four";
$part2 = "five";

$string = $part1' '$part2;