2012-04-21 19 views
0

我有單個字段,允許用戶在一個字符串中輸入不同的選項。所以,13123123 | 540 | 450解析出由特殊字符劃分的文本嗎?

我該如何將這三個值解析爲三個變量?

+0

您的意思是「特殊」或「亂」? – 2012-04-21 21:47:12

回答

1

您可以使用list把它們分爲三個不同的變量:

$str = '13123123|540|450'; 
list($one, $two, $three) = explode('|', $str); 

或者,你可以通過陣列indicies訪問他們,如果你想:

$str = '13123123|540|450'; 
$split = explode('|', $str); 
// $split[0] == 13123123 
0

使用基於正則表達式每個|之前的數字。所以第一個是[\d{8}]^\|]等等。

1

你可以嘗試以下方法:

$input = @$_POST["field"]; 

// Method 1: An array 

$options = explode ("|", $input); 

/* 
    The $options variable will now have the following: 
    $options[0] = "13123123"; 
    $options[1] = "540"; 
    $options[2] = "450"; 
*/ 

// Method 2: Assign to different variables: 

list($opt1, $opt2, $opt3) = explode ("|", $input); 

/* 
    The variables will now have the following: 
    $opt1 = "13123123"; 
    $opt2 = "540"; 
    $opt3 = "450"; 
*/ 

// Method 3: Regular expression: 

preg_match ("/(\w*)|(\w*)|(\w*)/i", $string, $matches); 

/* 
    The $options variable will now have the following: 
    $matches[0] = "13123123"; 
    $matches[1] = "540"; 
    $matches[2] = "450"; 
*/