2012-03-23 105 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';