Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string in an array with PHP

How can I replace a sub string with some other string for all items of an array in 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?

like image 891
hd. Avatar asked Feb 12 '11 08:02

hd.


People also ask

How can I replace part of a string in PHP?

The str_replace() function replaces some characters with some other characters in a string. This function works by the following rules: If the string to be searched is an array, it returns an array. If the string to be searched is an array, find and replace is performed with every array element.

How can I replace multiple words in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.

How do I remove a word from a string in PHP?

Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.

What is use of trim in PHP?

Definition and Usage. The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.


2 Answers

Why not just use str_replace without a loop?

$array = array('foobar', 'foobaz');
$out = str_replace('foo', 'hello', $array);
like image 78
netcoder Avatar answered Oct 12 '22 00:10

netcoder


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

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

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

That's much easier.

like image 23
NikiC Avatar answered Oct 12 '22 02:10

NikiC