2012-01-14 66 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'"; 
相关问题