替换数组PHP中的部分字符串
我的JSON响应如下所示替换数组PHP中的部分字符串,php,arrays,preg-replace,Php,Arrays,Preg Replace,我的JSON响应如下所示 ( [0] => stdClass Object ( [default] => false [loc] => http://somethingirrelevant.lol [temp] => '100' ) ) 我希望实现的是将[LOC]中的url更改为https 我尝试使用: $array = preg_replace('http','https' $array); 但这
(
[0] => stdClass Object
(
[default] => false
[loc] => http://somethingirrelevant.lol
[temp] => '100'
)
)
我希望实现的是将[LOC]
中的url更改为https
我尝试使用:
$array = preg_replace('http','https' $array);
但这完全破坏了阵列 您不能简单地调用数组,您可以做的是迭代数组并用键替换每个值
loc
:
foreach($array AS $key=>$value) {
if(isset($value['LOC'])) {
$array[$key]['LOC'] = preg_replace('http','https', $array);
}
}
您可以将数组强制转换为常规数组而不是对象:
if(!is_array($array)) $array = (array)array;
您有一个对象数组。数组键
0
是具有loc
属性的对象,您可以在此处使用str\u replace()
:
$array[0]->loc = str_replace('http://', 'https://', $array[0]->loc);
//$array[0]->loc = preg_replace('#http://#', 'https://', $array[0]->loc);
如果解码为数组:
$array = json_decode($json, true);
然后:
实际上,语法错误在我复制的原始代码中,但我应该注意到它。谢谢。不仅如此,正则表达式必须包含在分隔符之间;)我想补充一点,您应该使用wordboundary来避免将
https
替换为httpss
@Toto谢谢!上次我想去吃午饭的时候发的。
$array[0]['loc'] = str_replace('http://', 'https://', $array[0]['loc']);