用 PHP 替换数组中的字符串 [英] Replace string in an array with PHP

查看:28
本文介绍了用 PHP 替换数组中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用其他字符串替换 PHP 数组中所有项的子字符串?

How can I replace a sub string with some other string for all items of an array in PHP?

我不想用循环来做这件事.PHP 中是否有一个预定义的函数可以做到这一点?

I don't want to use a loop to do it. Is there a predefined function in PHP that does exactly that?

如何对数组的键执行此操作?

How can I do that on keys of array?

推荐答案

$array = array_map(
    function($str) {
        return str_replace('foo', 'bar', $str);
    },
    $array
);

但是 array_map 只是一个隐藏的循环.为什么不使用真实的?

But array_map is just a hidden loop. Why not use a real one?

foreach ($array as &$str) {
    $str = str_replace('foo', 'bar', $str);
}

那容易多了.

这篇关于用 PHP 替换数组中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆