2012-01-14 65 views
1

我有一個類似的字符串....PHP過濾字符串之前和之後的特定詞用不同長度

$string = "order apples oranges pears and bananas from username"; 

我怎樣才能得到它弄成這個樣子?這裏

$products = "apples oranges pears and bananas"; 
$username = "username"; 
+0

將「$ string」總是相同數量的元素,還是會改變?物品的順序將保持不變? – Silvertiger 2012-01-14 06:07:02

+0

你正在編寫你自己的查詢解析引擎嗎? – Brad 2012-01-14 06:07:13

+0

你有沒有試過正則表達式? – davogotland 2012-01-14 06:11:16

回答

0
$string = "order apples oranges pears and bananas from username"; 
list($products,$username) = explode(" from ", $string); 
$products = str_replace('order ', '', $products); 


//print results for verification 
var_dump(array($products,$username)); 

輸出:

array(2) { [0]=> string(32) "apples oranges pears and bananas" [1]=> string(8) "username" } 

但這不會處理不同的 「命令」 比 「命令」 等,也假設所有空白之間的空白ds是單個空格字符。您需要更復雜的代碼來處理多個案例,但這需要您提供更多信息。

+0

這更好,因爲它刪除了「訂單」謝謝 – afro360 2012-01-14 06:22:31

+0

@codercake給出了一個很好的答案。檢查這一個也(固定)只是爲了幫助你http://stackoverflow.com/a/8860540/410273 – andrewk 2012-01-14 06:37:44

3
list($products,$username) = explode("from", $string); 
+0

爲什麼我沒有想到,它太簡單了! – afro360 2012-01-14 06:20:29

0
<?php 

$string = "order apples oranges pears and bananas from username"; 

$part = explode("order",$string); 

$order = explode("from",$part[1]); 

echo $order[0]; 

echo $order[1]; 

?> 

檢查現場演示http://codepad.org/5iD02e6b

0

答案已被接受,但仍然..我的答案的優點是,如果在原始字符串中存在錯誤,則結果變量將爲空。這是很好的,因爲那樣很容易測試一切是否按照計劃進行:)

<?php 
    $string = "order apples oranges pears and bananas from username"; 
    $products_regex = "/^order\\s(.*)\\sfrom/i"; 
    $username_regex = "/from\\s(.*)$/i"; 
    $products_matches = array(); 
    $username_matches = array(); 
    preg_match($products_regex, $string, $products_matches); 
    preg_match($username_regex, $string, $username_matches); 
    $products = ""; 
    $username = ""; 

    if(count($products_matches) === 2 && 
      count($username_matches) === 2) 
    { 
     $products = $products_matches[1]; 
     $username = $username_matches[1]; 
    } 

    echo "products: '$products'<br />\nuser name: '$username'"; 
相關問題