How to Replace Multiple Values in PHP

How to replace multiple items from a text string in PHP?

You can pass arrays as parameters to str_replace(). Check the manual.

// Provides: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = ["fruits", "vegetables", "fiber"];
$yummy = ["pizza", "beer", "ice cream"];

$newPhrase = str_replace($healthy, $yummy, $phrase);

Search and replace multiple values with multiple/different values in PHP5?

You are looking for str_replace().

$string = 'blah blarh bleh bleh blarh';
$result = str_replace(
array('blah', 'blarh'),
array('bleh', 'blerh'),
$string
);

// Additional tip:

And if you are stuck with an associative array like in your example, you can split it up like that:

$searchReplaceArray = array(
'blah' => 'bleh',
'blarh' => 'blerh'
);
$result = str_replace(
array_keys($searchReplaceArray),
array_values($searchReplaceArray),
$string
);

PHP 7.1 replace multiple values with dynamic variables

You can use str_replace(), if you got arbitrary variables you can use compact() to put them in an array.

<?php
$str = "We have received ##AMOUNT## ##CURRENCY## for your OrderID n. ##ORDER_ID##";

$AMOUNT = 123;
$CURRENCY = 'GBP';
$ORDER_ID = 20123;

$find = ['##AMOUNT##','##CURRENCY##','##ORDER_ID##'];
$replace = compact('AMOUNT', 'CURRENCY', 'ORDER_ID');

echo str_replace($find, $replace, $str);

https://3v4l.org/1E2Mm

Result:

We have received 123 GBP for your OrderID n. 20123

If your looking for a way to just define your variables/placeholders once and then match and replace, you can do it like:

<?php
$str = "We have received ##AMOUNT## ##CURRENCY## for your OrderID n. ##ORDER_ID##";

$AMOUNT = 123;
$CURRENCY = 'GBP';
$ORDER_ID = 20123;

$find = ['AMOUNT', 'CURRENCY', 'ORDER_ID'];

echo str_replace(
array_map(function($v){ return '##'.$v.'##'; }, $find),
compact(...$find),
$str
);

https://3v4l.org/ekHYB

How to replace multiple values in php

This should work for you:

<?php

$string = "test1 test1 test2 test2 test2 test1 test1 test2";

echo $string . "<br />";
echo $string = strtr($string, array("test1" => "test2", "test2" => "test1"));

?>

Output:

test1 test1 test2 test2 test2 test1 test1 test2
test2 test2 test1 test1 test1 test2 test2 test1

Checkout this DEMO: http://codepad.org/b0dB95X5

PHP replace multiple values from an array to another one

Just use the mainarray's index to replace the $newcosts into the array.

foreach ($mainarray as $index => $subarray) {
$mainarray[$index]['cost'] = $newcosts[$index];
}

Because you will have an unused variable $subarray this way, it would be nicer to use a for loop:

for ($i = 0; $i < count($mainarray); $i++) {
$mainarray[$i]['cost'] = $newcosts[$i];
}

PHP curly braces replace multiple values

You regex has { and } metacharacters. You can't match them as is. You either escape it with backslash \ or use preg_quote().

Your code is pretty verbose with loops. You can pass array of values to replace with array of destination values and str_replace does the job pretty nicely.

<?php

function replace($Str,$values = []){
preg_match_all('/\{(\w+)\}/', $Str, $matches);
return str_replace($matches[0],$values,$Str);
}

$value1 = 'Apple';
$value2 = 'Orange';

$text = 'The colors of {value1} and {value2} are different.';

echo replace($text,[$value1,$value2]);

You also missed passing $value1 and $value2 to your function. My advice is to pass them in an array if there are multiple values to replace.

Find string and replace multiple values in a large text file using PHP

There is something not fully understandable in your question and code, of course it can be written in more optimal way.

However considering the current code you share, I suppose this changed variant the one you need.

<?php
$dir = "Example.txt";
$search = "<TR><TD>IP Address:</TD><TD>192.168.1.1</TD></TR>";
$replacement = " <TR><TD>Max Speed:</TD> <TD>10000</TD></TR>";
$maxbytes = "MaxBytes[192.168.1.1]: ";
$new_line = "MaxBytes[192.168.1.1]: \r";
$newmaxbytes = "MaxBytes[192.168.1.1]: 20000";

///// Change Max Speed
function find_line_number_by_string($dir, $search, $case_sensitive=false ) {
$line_number = [];
if ($file_handler = fopen($dir, "r")) {
$i = 0;
while ($line = fgets($file_handler)) {
$i++;
//case sensitive is false by default
if($case_sensitive == false) {
$search = strtolower($search);
$line = strtolower($line);
}
//find the string and store it in an array
if(strpos($line, $search) !== false){
$line_number[] = $i;
}
}
fclose($file_handler);
}else{
return "File not exists, Please check the file path or dir";
}

return $line_number;
}

$line_number = find_line_number_by_string($dir, $search);
var_dump($line_number);

$lines = file($dir, FILE_IGNORE_NEW_LINES);
if(!empty($line_number)) {
$lines[$line_number[0]] = $replacement;
}

file_put_contents($dir , implode("\n", $lines));

///// Change MaxBytes

$contents = file_get_contents($dir);
$new_contents= "";
if( strpos($contents, $maxbytes) !== false) { // if file contains ID
$contents_array = preg_split("/\\r\\n|\\r|\\n/", $contents);
foreach ($contents_array as &$record) { // for each line
if (strpos($record, $maxbytes) !== false) { // if we have found the correct line
$new_contents .= $new_line; // change record to new record
}else{
$new_contents .= $record . "\n";
}
}

file_put_contents($dir, $new_contents, LOCK_EX);

$fhandle = fopen($dir,"r");
$content = fread($fhandle,filesize($dir));
$content = str_replace($maxbytes, $newmaxbytes, $content);
$fhandle = fopen($dir,"w");
fwrite($fhandle,$content);
fclose($fhandle);

}else{}

?>

If it does not works the way you need, please contact me, I'll update the answer..



Related Topics



Leave a reply



Submit