Lalarukh khan
Lalarukh khan

Reputation: 170

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

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:

Result

Expected Output:

[Expected Result

Upvotes: 1

Views: 1023

Answers (3)

nice_dev
nice_dev

Reputation: 17805

Non-regex way:

Make a hashmap of your lang characters and loop your string character by character. If the current character is set in the map, add those span tags, else just append the current character.

<?php

$str = "we are checking it";   
$langs = array ('w', 'c', 'i');
$lang_map = array_flip($langs);

$new_str = "";

for($i = 0; $i < strlen($str); ++$i){
    if(isset($lang_map[ $str[$i] ])){
        $new_str .= "<span style='color:red;'>".$str[$i]."</span>";
    }else{
        $new_str .= $str[$i];
    }
}

echo $new_str;

Online Demo

Regex way:

You can use preg_replace to replace each character from lang surrounded by span tags like below:

<?php

$str = "we are checking it";   
$langs = array ('w', 'c', 'i');
$lang_regex = preg_quote(implode("", $langs));

$str = preg_replace("/[$lang_regex]/", "<span style='color:red;'>$0</span>", $str);

echo $str;

Online Demo

Upvotes: 2

Abhay Bisht
Abhay Bisht

Reputation: 184

You can use preg_replace function :-

<?php

$str = "wi are checking it";   
$langs = array ('w', 'i');

$pattern = array();
$htm = array();


for ($i = 0; $i < count($langs) ; $i++) {
    $pattern[$i] = "/".$langs[$i]."/";
    $htm[$i] = "<span style='color:red;'>".$langs[$i]."</span>";
}

$limit = -1;
$count = 0;

$new = preg_replace($pattern, $htm, $str, $limit, $count);

#echo htmlspecialchars($str)."<br>";
echo ($new);
    
?>

Your required Result :-

<span style='color:red;'>w</span><span style='color:red;'>i</span> are checking it

Sorry but you can't replace 'c' character because the replacing string also contains 'c' char (i.e. c in ...style = "color:red") so this function re-replace this 'c' char and generate a bugged string... šŸ˜…

Fix this bug by yourself For reference read this

Upvotes: 0

Faizul Islam
Faizul Islam

Reputation: 77

You can try with this method.

$youText  = "wi are checking it";
$find     = ["wi", "it"];
$replace  = ["we", "its"];
$result   = str_replace($find, $replace, $youText);
echo $result;

Upvotes: 0

Related Questions