2014-03-07 88 views
1

更新:$字符串可以有一個或多個「;」。我必須照顧最後一個。由字符串的最後一次出現在字符串中返回第一個和最後一個部分導致字符串爆炸

$string = "Hello world; This is a nice day; after"; 

$out[] = trim(substr(strrchr ($string, ";"), 1)); 
$out[] = trim(substr(strrchr ($string, ";"), 0)); 

var_dump($out); 

結果: 陣列(2){ [0] => 串(3) 「後」 [1] => 串(5) 「;之後」 }

但我需要的是:

陣列(2){ [0] => 串(3) 「後」 [1] => 串(5)的「Hello world;這是一個美好的一天「 }

我應該怎麼做?

+0

的信息以及與玩什麼'爆炸()'呢? – fedorqui

+0

嘗試爆炸()但字符串可以varry,至少有一個「;」但可以有更多。我必須照顧最後的「;」並且只能在那裏爆炸。 @fedorqui你告訴我如何玩? – caramba

+0

so explode(「;」,$ out)和explode(「」,$ out) – Orlo

回答

6
 
$dlm = "; "; 
$string = "Hello world; This is a nice day; after"; 

$split = explode($dlm,$string); 
$last = array_pop($split); 
$out = array($last,implode($dlm,$split)); 

2

嘗試

string = "Hello world; This is a nice day; after"; 
$out[] = trim(substr(strrchr($string, ";"), 1)); 
$out[] = trim(substr($string, 0, strrpos($string, ";")+1)); 

觀看演示here

0

你可以嘗試使用:

$string = "Hello world; This is a nice day; after"; 
$parts = explode(';', $string); 
$output = array(trim(array_pop($parts)), implode(';', $parts)); 

var_dump($output); 

輸出:

array (size=2) 
    0 => string 'after' (length=5) 
    1 => string 'Hello world; This is a nice day' (length=31) 
0
$string = "Hello world; This is a nice day; after"; 
$offset = strrpos($string,';'); 

$out[] = substr($string, $offset+1); 
$out[] = trim(substr($string, 0, $offset)); 
print_r($out); 
+0

與mine.but相同但你比我快,因此我刪除了我的。 – krishna

0
$string = "Hello world; This is a nice day; after"; 
/// Explode it 
$exploded_string = explode(";", $string); 
/// Get last element 
$result['last_one'] = end($exploded_string); 
/// Remove last element 
array_pop($exploded_string); 
/// Implode other ones 
$result['previous_ones'] = implode(";", $exploded_string); 

print_r($result); 

結果將是:

Array ([last_one] => after [previous_ones] => Hello world; This is a nice day) 
相關問題