简体   繁体   中英

Replacing items in an array using two regular expressions

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:9bc0d67a-0@acoregroup.com
    [1] => mailto:347c6b@acoregroup.com
    [2] => mailto:3b3cce0a-0@acoregroup.com
    [3] => mailto:9b690cc@acoregroup.com
    [4] => mailto:3b7f59c1-4bc@acoregroup.com
    [5] => mailto:cc62c936-7d@acoregroup.com
    [6] => mailto:5270f9@acoregroup.com
}

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:9bc0d67a-0@acoregroup.com" with "9bc0d67a-0@acoregroup.com" in each index of the array.

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

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.

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);

对于这种类型的替换,您应该使用str_replace,它的速度更快,在线文档强烈建议

   $array = str_replace('mailto:', '', $array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM