2010-02-08 66 views
0

客戶ID字面已經CUSTOMER_ID + Domain_details,如:998787+nl,現在我只是想有998787而不是+nl,這可怎麼在php來達到的這個如何擺脫在PHP中的字符串元素?

問:

我有一個像9843324+nl數量和現在我想擺脫所有元素,包括+和事後結束,只有9843324等,我應該如何做到這一點在PHP?

現在我有$o_household->getInternalId返回我9843324+nl但我想要9843324,我該怎麼做到這一點?

謝謝。

謝謝。

更新

list($customer_id) = explode('+',$o_household->getInternalId()); 

這是否會解決我的問題?

+0

Rachel,http://stackoverflow.com/questions/2210347/how-to-get-rid-of-extra-elements-in-string-literal-in-php有你接受的答案。兩者之間沒有區別,爲什麼要問另一個問題? – 2010-02-08 16:14:50

+0

它確實有區別,實際上我不打算在這裏提到這個問題 – Rachel 2010-02-08 16:18:28

+0

這個答案並沒有從客戶ID中刪除域的詳細信息 – Rachel 2010-02-08 16:19:19

回答

1
<?php 
$plusSignLoc = strpos($o_household->getInternalId, "+"); 
$myID = substr($o_household->getInternalId, 0, $plusSignLoc); 

//Debug (Verification) 
echo $myID; 
?> 

這會找到+號,並確保它後面的任何內容都會被刪除。

2

如果您不想保留前導零,只需將其轉換爲整數即可。

$theID = (int)"9843324+nl"; 
// $theID should now be 9843324. 

如果+只是一個分隔符和某些材料之前可以是非數,使用

$val = "9843324+nl"; 
$theID = substr($val, 0, strcspn($val, '+')); 
// $theID should now be "9843324". 
+0

我沒有這裏的前導零,只有customer_id + domain_name,但我想遠程'+ domain_name'和只有customer_id,希望我在這裏明確自己。 – Rachel 2010-02-08 16:08:47

+0

@Rachel:'$ theID'是你的customer_id。 – kennytm 2010-02-08 16:12:28

1

如果你需要它仍然是一個字符串值,可以使用substr切斷串到它的起始索引從最後一個字符第三,省略域細節+nl

$customer_id = substr($o_household->getInternalId, 0, -3); 
2

簡單的方法?只需將它投射到一個整數,它會放棄額外的東西。

<?php 
$s = '998787+nl'; 
echo (int)$s; 
?> 

輸出:

998787 
1

作爲一個稍微更通用的解決方案,這個正則表達式將刪除一切不是從字符串$str一個數字,並把新的字符串(數字設定,所以它可以被看作一個整數)轉換成$num

$num = preg_replace('/[^\d]/', '', $str); 
+0

@Downvoter,請評論爲什麼。這與提問者想要的完全一樣,並且爲所有其他建議的方法提供了一個很好的選擇。 – Yacoby 2010-02-09 14:32:53