John Davidson

arrays - Replace values inside foreach loop and show only one string - PHP

0 comments
Message:


I want to replace my values of string according to the position coming from JSON array.
e.g. JSON has 0,3,6 numbers coming as offset(position) attribute. I want to get each value from my loop and make it replaceable inside my string. But Its getting only last value outside loop that is '6'(offset) and replacing 'c' with red color variable 'c'.
Here's my code:


function str_replace_first($search, $replace, $subject)
{
$search = '/'.preg_quote($search, '/').'/';
return preg_replace($search, $replace, $subject, 1);
}

$str = "we is chekin";
foreach ($json2['matches'] as $key=>$val) {
$takeoffset = $val['offset']; // getting offset value from JSON
$convertingoffset = $str[$takeoffset]; //convert number to character
$ofsetsplit = '<span style="color: red;">'.$convertingoffset.'</span>'; //value to replace
$realone = $convertingoffset; //value to be replaced
$result_offset = str_replace_first($realone, $ofsetsplit, $str); //replacing
}
echo $result_offset; //getting result

When I replace inside loop:



When I replace outside loop, then only last value of position showing changed only



My Answer:
"abcdefg";$json = [0, 3, 6];$colors = ['red', 'green', 'blue'];foreach ($json as $offset) {_ $c = $colors[$offset/3];_ $str = str_replace_first($str[$offset], "$str[$offset]", $str);_}echo $str;

Rate this post

5 of 5 based on 4252 votes

Comments




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