[英]Using Regex to find if the string is inside the array and replace it + PHP
[英](PHP) Replace string of array elements using regex
我有一個數組
Array
(
[0] => "http://example1.com"
[1] => "http://example2.com"
[2] => "http://example3.com"
...
)
我想使用RegEx將http
替換為每個元素的https
。 我試過了:
$Regex = "/http/";
$str_rpl = '${1}s';
...
foreach ($url_array as $key => $value) {
$value = preg_replace($Regex, $str_rpl, $value);
}
print_r($url_array);
但是結果數組仍然相同。 任何想法?
您實際上打印了一個數組而不更改它。 為什么為此需要正則表達式?
根據Casimir et Hippolyte的提示進行編輯:
這是使用正則表達式的解決方案:
$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);
沒有正則表達式:
$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);
首先,您根本不需要修改數組值。 在您的示例中,您正在操作數組值的副本。 實際修改數組元素:
foreach($foo as $key => &$value) {
$value = 'new value';
}
for($i = 0; $i < count($foo); $i++) {
$foo[$i] = 'new value';
}
回到您的問題,您也可以不使用正則表達式來解決問題(只要有可能,最好不使用正則表達式(問題少,調試簡單,測試簡單等)。)
$tmp = array_map(static function(string $value) {
return str_replace('http://', 'https://', $value);
}, $url_array);
print_r($tmp);
編輯 :
正如Casimir指出的那樣,由於str_replace可以將array作為第三個參數,因此您可以執行以下操作:
$tmp = str_replace('http://', 'https://', $url_array);
此表達式也可能起作用:
^http\K(?=:)
我們可以添加更多邊界,例如在必要時驗證URL,例如:
^http\K(?=:\/\/[a-z0-9_-]+\.[a-z0-9_-]+)
$re = '/^http\K(?=:\/\/[a-z0-9_-]+\.[a-z0-9_-]+)/si';
$str = ' http://example1.com ';
$subst = 's';
echo preg_replace($re, $subst, trim($str));
https://example1.com
在regex101.com的右上角對表達式進行了說明,如果您希望對其進行探索/簡化/修改,並且在此鏈接中 ,您可以根據需要觀看它與某些示例輸入的匹配方式。
jex.im可視化正則表達式:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.