Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP replace characters in an array

I have data like this in my array first_name, last_name,....

I am looking for an array to replace the _ with a space..is this possible?

I took alook at http://php.net/manual/en/function.array-replace.php but I am not sure if this is what I want.

like image 580
user979331 Avatar asked Nov 09 '12 18:11

user979331


People also ask

How can I replace multiple characters 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 you replace values in an array?

To replace an element in an array: Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.

What is use of Preg_replace in PHP?

PHP | preg_replace() Function The preg_replace() function is an inbuilt function in PHP which is used to perform a regular expression for search and replace the content.

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.


2 Answers

Just with str_replace, it takes either strings or arrays in all arguments that matter:

var_dump(str_replace('_',' ',array('foo_bar','lorem_ipsum')));


array(2) {
  [0]=>
  string(7) "foo bar"
  [1]=>
  string(11) "lorem ipsum"
}
like image 155
Wrikken Avatar answered Oct 14 '22 17:10

Wrikken


foreach($array as $key=>$value){
  $array[$key]=str_replace("_"," ",$value);
}

That should do it, right?

like image 35
Landon Avatar answered Oct 14 '22 17:10

Landon