2010-02-25 48 views
0

我有一個字符串的preg_replace所有字符,直到達到一定的一個

&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5& 

,我不得不刪除,也就是說,這部分& |手機| 3 | 120 | 1 &(從安培並用安培結束)僅知道所述第一數目最多垂直線(185601651932)

,使得在結果我將不得不

&168491968426|mobile|3|100|1&114192088691|mobile|3|555|5& 

我怎麼能用PHP preg_replace函數做到這一點。行(|)分隔值的數量總是相同,但id仍然具有靈活的模式,而不依賴於&符號之間的行數。

謝謝。

P.S.另外,我會非常感謝鏈接到一個簡單的寫在正則表達式中的資源。有很多人在谷歌:)但也許你碰巧有一個真正偉大的鏈接

回答

1
preg_replace("/&185601651932\\|[^&]+&/", ...) 

廣義,

$i = 185601651932; 
preg_replace("/&$i\\|[^&]+&/", ...); 
+0

耶!而已!除了,我不需要最後&,所以它只是 preg_replace(「/&185601651932 \\ | [^&] + /」,...) 非常感謝 – dr3w 2010-02-25 11:08:41

0

重要提示:不要忘記用preg_quote()逃脫你的電話號碼:

$string = '&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&'; 
$number = 185601651932; 
if (preg_match('/&' . preg_quote($number, '/') . '.*?&/', $string, $matches)) { 
    // $matches[0] contains the captured string 
} 
0

在我看來,你應該使用不是字符串另一個數據結構來處理這些數據。 我會做這樣的事情要在結構的數據像

Array(
    [id] => Array(
    [field_1] => value_1 
    [field_2] => value_2 
) 
) 

你大量的字符串可以按摩到這樣的結構:

$data_str = '168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&'; 
$remove_num = '185601651932'; 

/* Enter a descriptive name for each of the numbers here 
- these will be field names in the data structure */ 
$field_names = array( 
    'number', 
    'phone_type', 
    'some_num1', 
    'some_num2', 
    'some_num3' 
); 

/* split the string into its parts, and place them into the $data array */ 
$data = array(); 
$tmp = explode('&', trim($data_str, '&')); 
foreach($tmp as $record) { 
    $fields = explode('|', trim($record, '|')); 
    $data[$fields[0]] = array_combine($field_names, $fields); 
} 

echo "<h2>Data structure:</h2><pre>"; print_r($data); echo "</pre>\n"; 
/* Now to remove our number */ 
unset($data[$remove_num]); 
echo "<h2>Data after removal:</h2><pre>"; print_r($data); echo "</pre>\n";