2012-03-23 108 views
0

我有一個移動電話$numbers列表,我必須更改它們,前綴數39,如果數字本身以$prefixes數組中的一個開頭。preg_replace替換前綴後綴加自己

我現在不知道如何反向引用找到的前綴或(這是相同的)如何獲得匹配的前綴)。我試過以下,但它不工作:

$numbers = array('3284121532', '3478795687'); // the subject 
$prefixes = array('328', '347');    // (will be) the pattern 

// Build regex for each element of $prefix array 
$pattern = array_map(function($s) { return "/^$s/"; }, $prefixes); 
$replace = "39\{$1}"; 

var_dump(preg_replace($pattern, $replace, $numbers); 

任何幫助,將不勝感激,謝謝。

+0

您不在代碼中的任何位置使用'preg_replace'。 – kba 2012-03-23 07:48:26

+0

@KristianAntonsen對不起,修好了,謝謝。 – gremo 2012-03-23 07:50:31

回答

2
$numbers = array(3284121532, 3478795687); 
$prefixes = implode('|',array(328, 347)); 

$numbers = array_map(function($n) use ($prefixes) { 
    return preg_replace("/^($prefixes)/", '39$1', $n); 
}, $numbers); 

print_r($numbers); 

上面會輸出

Array 
(
    [0] => 393284121532 
    [1] => 393478795687 
) 
+0

'$ prefixes'數組是動態的,爲什麼在preg_replace中你使用的是'328 | 347'? – gremo 2012-03-23 07:57:57

+0

@格雷莫它現在是動態的。 – kba 2012-03-23 08:00:25

+0

謝謝,作品,我已經稍微調整了你的解決方案。基本上我的錯誤是沒有添加(組,我想),並使用參考周圍的「{}」。再次感謝。 – gremo 2012-03-23 08:03:16

0

僅在單引號內使用$1

$replace = '39$1; 

你可以做到這一點與

$results = array_map(function($s) { 
    return preg_replace("/^(".join('|' . $prefixes) . "\d+)/", '39$1', $s); 
}, $numbers); 
+0

我不確定它爲什麼會降低效果。似乎是合法的解決方案 – 2016-01-11 13:58:26

0

如果你想在你更換了整場比賽,你可以使用$0

$replace = '39$0';