2012-03-27 198 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";