2012-01-14 3 views
1

다양한 길이의 특정 단어 후 ....PHP 필터 문자열 전에 나는이 비슷한 문자열을

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

어떻게하면이 같은 무언가로받을 수 있나요? 여기

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

은 "$ 문자열은"항상 같은 수의 원소, 또는이 변경됩니다 뜻을 따라 가면 테스트하기 쉽기 때문 좋다? 항목의 순서는 동일하게 유지됩니까? – Silvertiger

+0

독자적인 쿼리 구문 분석 엔진을 작성하고 있습니까? – Brad

+0

정규식을 사용해 보셨습니까? – davogotland

답변

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" } 

하지만 다른 처리하지 않습니다 또한 "순서"이외의 "명령"을 wor 사이의 모든 공백을 가정합니다. ds는 단일 공백 ​​문자입니다. 여러 사례를 처리하려면 더 복잡한 코드가 필요하지만 더 많은 정보가 필요합니다.

+0

이것은 "순서"를 제거하기 때문에 더 좋습니다. – afro360

+0

@codercake는 훌륭한 답을주었습니다. 이 문제도 해결하려면 http://stackoverflow.com/a/8860540/410273을 참조하십시오. – andrewk

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

왜 그렇게 생각하지 않았는가? – afro360

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'";