2010-02-25 52 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";