How to Replace Multiple Items from a Text String 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);

how to Str_replace for multiple items

You can use strtr() and an associative array to do this:

<?php
$text = "Text about -- and -+- !";
$replacements = [
"--" => "/",
"-+-" => ":",
];
echo strtr($text, $replacements); // Text about / and : !

To add more replacements, simply keep adding more elements to the $replacements array. Index is the string to look for, value is the replacement.

  • Demo
  • strtr() reference

PHP how to replace multiple strings

I think you're looking for the explode and implode functions. You can do something like this which breaks your string into an array, you can modify the array elements, then combine them back into a string.

$str = "have:a:good:day:";

$tokens = explode(":", $str);
//$tokens => ["have", "a", "good", "day", ""]

$tokens[2] = "newString1";
//$tokens => ["have", "a", "newString1", "day", ""]

$str2 = implode(":", $tokens);
//$str2 => "have:a:good:day:"

Alternatively if you just want to replace certain words in the string, you can use the str_replace function to replace one word with another. Eg.

$str = "have:a:good:day:";
$str2 = str_replace("good", "newString1", $str);
//$str2 => "have:a:newString1:day:";

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..

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

Replace multiple words with multiple parameters - str_replace()

Do it like this

$str="We have received [MACHINE_NAME] for service. Your service request id is [NEW_SERVICE_ID]. Thank you.";
$remove = array("[MACHINE_NAME]", "[NEW_SERVICE_ID]");
$add = array("YOURMACHINE_NAME", "SERVICE_ID");
echo $onlyconsonants = str_replace($remove, $add,$str );

How to replace multiple strings in PHP using str_replace?

It appears you are misunderstanding how to use str_replace to replace multiple strings. The first argument is an array of string you want to replace, and the second is another array of matching strings to replace them with.

You probably intended to do something like this.

str_replace(array(".mp4", "clip_"), array("", ""), "clip_sample_data.mp4")

Which will return the following string.

"sample_data"

And since you want to replace everything with just a blank string, this code can be reduced to this.

str_replace(array(".mp4", "clip_"), "", "clip_sample_data.mp4")

Str_replace for multiple items

str_replace() can take an array, so you could do:

$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);

Alternatively you could use preg_replace():

$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);


Related Topics



Leave a reply



Submit