John Davidson

arrays - Getting value in loop and replace it in string once in PHP

0 comments
Message:


I'm trying to find & replace my values from inside string after getting values from inside loop.
When I replace my string from inside loop then(that method isn't suitable)as it replaces one by one until loop ends and I get a lot of strings with single replacements at each.
I'm trying to replace the whole string with loop values outside only once.
Here's my code.


$str = "wi are checking it";   
$langs = array ('w', 'c', 'i');
foreach ($langs as $lang) {
$search = $lang;
$url[] = "<span style='color:red;'>".$search."</span>";
$qw[] = $search;
}
$op = implode("", $url);
$er = implode("", $qw);
echo $op."<br>";
echo $er."<br>";
$new = str_replace($er, $op, $str);
echo $new;

It's output:



Expected Output:


[



My Answer:
a way to loop through an array in PHP and replace a specific value in a string only once. Here's an example of how you can achieve this:

php
$array = ['apple', 'banana', 'cherry'];
$string = 'I like to eat fruits like {fruit1}, {fruit2}, and {fruit3}';

foreach ($array as $key => $value) {
$placeholder = '{fruit' . ($key + 1) . '}';
$string = preg_replace('/' . preg_quote($placeholder, '/') . '/', $value, $string, 1);
}

echo $string;


In this code snippet, we have an array of fruits and a string with placeholders for each fruit. We loop through the array and replace each placeholder in the string with the corresponding fruit value. The `preg_replace` function is used with a limit of 1 to ensure that each placeholder is replaced only once.

After running this code, the output will be:

I like to eat fruits like apple, banana, and cherry


This way, you can dynamically replace values in a string based on an array in PHP.

Rate this post

5 of 5 based on 3660 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us