tags:

views:

122

answers:

4

Can you use two regex in preg_replace to match and replace items in an array? So for example:

Assume you have:

Array 
(
    [0] => mailto:[email protected]
    [1] => mailto:[email protected]
    [2] => mailto:[email protected]
    [3] => mailto:[email protected]
    [4] => mailto:[email protected]
    [5] => mailto:[email protected]
    [6] => mailto:[email protected]
}

and you have two variables holding regex strings:

 $reg = '/mailto:[\w-]+@([\w-]+\.)+[\w-]+/i';
 $replace = '/[\w-]+@([\w-]+\.)+[\w-]+/i';

can I:

preg_replace($reg,$replace,$matches);

In order to replace "mailto:[email protected]" with "[email protected]" in each index of the array.

+1  A: 
foreach($array as $ind => $value)
  $array[$ind] = preg_replace('/mailto:([\w-]+@([\w-]+\.)+[\w-]+)/i', '$1', $value);

EDIT: gahooa's solution is probably better, because it moves the loop inside preg_replace.

Matthew Flaschen
what does $1 represent?
Graham
The first matching group. In this case whatever "([\w-]+@([\w-]+\.)+[\w-]+)" matches.
Matthew Flaschen
+3  A: 

You could try this:

$newArray = preg_replace('/mailto:([\w-]+@([\w-]+\.)+[\w-]+)/i', '$1', $oldArray);

Haven't tested

See here: http://php.net/manual/en/function.preg-replace.php

gahooa
+1  A: 

I think that you are looking for the '$1' submatch groups, as others have already pointed out. But why can't you just do the following:

// strip 'mailto:' from the start of each array entry
$newArray = preg_replace('/^mailto:\s*/i', '', $array);

In fact, seeing as your regex doesn't allow the use of ':' anywhere in the email addresses, you could do it with a simple str_replace():

// remove 'mailto:' from each item
$newArray = str_replace('mailto:', '', $array);
too much php
+1  A: 

For this type of substitution you should use str_replace it is mutch faster and strongly suggested by the online documentation:

   $array = str_replace('mailto:', '', $array);
Eineki
Definitely agree on the use of `str_replace` in this situation. It's more than twice as fast than gahooa's regex. For the record, I also tried a loop with a `substr($str, 7)` construction. It's faster than the regex, but does not beat `str_replace`.
Geert