Str_Replace with Array

str_replace with array

str_replace with arrays just performs all the replacements sequentially. Use strtr instead to do them all at once:

$new_message = strtr($message, 'lmnopq...', 'abcdef...');

How can I use an array in str_replace() function?

You can do that by passing an array as first argument:

$res = str_replace(array(' ', '-', ','), '', $str);

You can test it here at phpfiddle.org.

str_replace() PHP's function let you choose if the three
parameters will be a single value or an array.

php str_replace array by array

Unfortunately str_replace doesn't have a built-in option to limit the number of replacements. You can use preg_replace instead, as this function has as 4th parameter the limit of occurrences.

Your code needs to take into consideration that the strings to replace are now regex so you need to add a delimited (e.g. the /).

Working code below:

$text = 'The Book has read by Dog and Cat then Book show Apple not Dog';
$array1 = array('1','2','3','4','5','6');
$array2 = array('/Book/','/Dog/','/Cat/','/Book/','/Apple/','/Dog/');
echo preg_replace($array2, $array1, $text, 1);

The output is

The 1 has read by 2 and 3 then 4 show 5 not 6

PHP str_replace with array() not working ? (have example)

This code removes parentheses (, ) from the following string:

(test) i'm test"

$string = "(test) i'm test";
echo str_replace(array( '(', ')' ), '', $string);

The results after using the str_replace() function:

test i'm test"

str_replace() with associative array

$text = strtr($text, $array_from_to)

By the way, that is still a one dimensional "array."

str_replace in array, and append text at the end

You can use preg_replace as an one-stop shop for this type of manipulation:

$array = preg_replace('/(.*);VALUE=DATE(.*)/', '$1$2T000000', $array);

The regular expression matches any string that contains ;VALUE=DATE and captures whatever precedes and follows it into capturing groups (referred to as $1 and $2 in the replacement pattern). It then replaces that string with $1 concatenated to $2 (effectively removing the search target) and appends "T000000" to the result.

PHP str_replace array

use array_map() with callback

    $setValues = array("test1", "test2", "testurl");
$change = array_map(function($val) { return "?"; }, $setValues);
$change = join(",", $change);
echo $change;// outputs => ?,?,?


Related Topics



Leave a reply



Submit