I have a list of mobile phone $numbers
and i have to change them, prefixing the number 39
, if the number itself starts with one in $prefixes
array.
I don't now how to back referencing to the found prefix, or (it's the same) how to get the matched prefix). I've tried the following but it's not working:
$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);
Any help would be appreciated, thanks.
$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);
The above will output
Array
(
[0] => 393284121532
[1] => 393478795687
)
Just use $1
within single quote.
$replace = '39$1;
You can do that with
$results = array_map(function($s) {
return preg_replace("/^(".join('|' . $prefixes) . "\d+)/", '39$1', $s);
}, $numbers );
If you want to include the whole match in your replacement, you can use $0
:
$replace = '39$0';