2012-03-27 239 views
8

我需要将字符串拆分为两部分。该字符串包含用空格隔开的话,可以包含任意数量的话,e.g:将字符串拆分为两部分

$string = "one two three four five";

第一部分需要包含所有的话,除了最后一个。 第二部分只需要包含最后一个单词。

任何人都可以建议吗?

编辑:这两部分需要作为字符串返回的,不是数组,e.g:

$part1 = "one two three four";

$part2 = "five";

+1

strrpos将是一个很好的起点。该手册有更多。 – GordonM 2012-03-27 14:44:55

回答

21

几种方法,你可以去了解它。

数组操作:

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

从逻辑上讲,由于OP使用的是字符串而不是数组,所以我会说使用“非”数组选项,因为它们不需要数组(使得代码看起来更合理,因为它只是使用字符串)但是否有任何性能差异? – James 2015-09-12 19:00:42

7

你需要的是分裂的最后空间输入字符串。现在最后一个空间是一个没有空间的空间。所以,你可以用式断言找到最后的空间:

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

干净简单! +1 – 2017-08-23 20:37:59

5

看一看在PHP中explode功能

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

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

这应做到:

$arr = explode(' ', $string); 
$second = array_pop($arr); 
$result[] = implode(' ', $arr); 
$result[] = $second; 
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

1

像这样的事情会做它,虽然它不是特别优雅。

$string=explode(" ", $string); 
$new_string_1=$string[0]." ".$string[1]." ".$string[2]." ".$string[3]; 
$new_string_2=$string[4]; 
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]

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