2011-11-23 25 views
0

我有一個這樣的字符串:PHP列提取

S="str1|str2|str3" 

我想從s擷取另一個字符串,將只包含

t="str1|str2" 

其中|是分隔符

謝謝

回答

2
$string = "str1|str2|str3"; 
$pieces = explode('|', $string); // Explode on '|' 
array_pop($pieces); // Pop off the last element 
$t = implode('|', $pieces); // Join the string back together with '|' 

或者,使用字符串操作:

$string = "str1|str2|str3"; 
echo substr($string, 0, strrpos($string, '|')); 

Demo

+0

我喜歡這個主意+鏈接, 感謝兄弟 – Br3x

+0

@Zonta您太客氣了。 - 如果輸入字符串只會像你例如,使用第二個版本(字符串操作),因爲它效率更高。 – nickb

+0

是的,我的輸入字符串只會像我的前, 乾杯;) – Br3x

0
implode("|", array_slice(explode("|", $s), 0, 2)); 

不是一個非常靈活的解決方案,而是適用於你的測試用例。

或者,您也可以利用explode()的第三PARAM limit,就像這樣:

implode("|", explode("|", $s, -1)); 
0
$s = 'str1|str2|str3'; 
$t = implode('|', explode('|', $s, -1)); 
echo $t; // outputs 'str1|str2' 
0

那麼,得到沒有最後一個元素的相同字符串?

這工作:

print_r(implode('|', explode('|', 'str1|str2|str3', -1))); 

使用帶有負限制所以它返回所有的字符串沒有最後一個元素爆炸,然後再次爆的元素。

+0

它也可以;) 感謝兄弟! – Br3x

0

這個例子應該設置你的正確路徑

$str = "str1|str2|str3"; 
$pcs = explode("|", $str); 
echo implode(array_slice($pcs, 0, 2), "|"); 
+0

Yesss!謝謝Carl;) – Br3x