简体   繁体   中英

(PHP) Replace string of array elements using regex

I have an array


Array
(
    [0] => "http://example1.com"
    [1] => "http://example2.com"
    [2] => "http://example3.com"
    ...
)

And I want to replace the http with https of each elements using RegEx. I tried:

$Regex = "/http/";
$str_rpl = '${1}s';
...
foreach ($url_array as $key => $value) {
  $value = preg_replace($Regex, $str_rpl, $value);
}
print_r($url_array);

But the result array is still the same. Any thought?

You actually print an array without changing it. Why do you need regex for this?

Edited with Casimir et Hippolyte's hint:

This is a solution using regex:

$url_array = array
(
    0 => "http://example1.com",
    1 => "http://example2.com",
    2 => "http://example3.com",

);

$url_array = preg_replace("/^http:/i", "https:", $url_array);
print_r($url_array);

PHP Demo

Without regex:

$url_array = array
(
    0 => "http://example1.com",
    1 => "http://example2.com",
    2 => "http://example3.com",

);

$url_array = str_replace("http://", "https://", $url_array);
print_r($url_array);

PHP Demo

First of all, you are not modifying the array values at all. In your example, you are operating on the copies of array values. To actually modify array elements:

  1. use reference mark
foreach($foo as $key => &$value) {
   $value = 'new value';
}
  1. or use for instead of foreach loop
for($i = 0; $i < count($foo); $i++) {
   $foo[$i] = 'new value';
}

Going back to your question, you can also solve your problem without using regex (whenever you can, it is always better to not use regex [less problems, simpler debugging, testing etc.])

$tmp = array_map(static function(string $value) {
    return str_replace('http://', 'https://', $value);
}, $url_array);

print_r($tmp);

EDIT :

As Casimir pointed out, since str_replace can take array as third argument, you can just do:

$tmp = str_replace('http://', 'https://', $url_array);

This expression might also work:

^http\K(?=:)

which we can add more boundaries, and for instance validate the URLs, if necessary, such as:

^http\K(?=:\/\/[a-z0-9_-]+\.[a-z0-9_-]+)

DEMO

Test

$re = '/^http\K(?=:\/\/[a-z0-9_-]+\.[a-z0-9_-]+)/si';
$str = '  http://example1.com  ';
$subst = 's';

echo preg_replace($re, $subst, trim($str));

Output

https://example1.com

The expression is explained on the top right panel of regex101.com , if you wish to explore/simplify/modify it, and in this link , you can watch how it would match against some sample inputs, if you like.

RegEx Circuit

jex.im visualizes regular expressions:

在此处输入图片说明

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