dotJoon
1
<?php
$myVar1='[COLOR="#FF0000"]a[/COLOR]pcdzefg[COLOR="#FF0000"]a[/COLOR]zbcdr[COLOR="#FF0000"]a[/COLOR]jvr';
$myVar2='egh[COLOR="#FF0000"]a[/COLOR]wqbss[COLOR="#FF0000"]a[/COLOR]tyuv[COLOR="#FF0000"]aa[/COLOR]vxi';
?>
I have a variable “$myVar” like the above.
I like to insert numbering inside “$myVar” before “a”;
myTarget result is like the below.
$target_myVar1='[COLOR="#FF0000"]1a[/COLOR]pcdzefg[COLOR="#FF0000"]2a[/COLOR]zbcdr[COLOR="#FF0000"]3a[/COLOR]jvr';
$target_myVar2='egh[COLOR="#FF0000"]1a[/COLOR]wqbss[COLOR="#FF0000"]2a[/COLOR]tyuv[COLOR="#FF0000"]3a4a[/COLOR]vxi';
How can I change $myVar to $target_myVar like the above?
Here’s how i’d do it. There’s probably a better way.
$count = 0;
$string = preg_replace_callback('~a~',function ($match) use (&$count) { $count += 1; return $count."a"; },$string);
Not the cleaner way of doing it, but want you to see how you can use a string as an array,
$var = "apcdzefgazbcdrajvr";
$newVar = "";
$counter = 1;
for($i = 0; $i < strlen($var); $i++) {
if($var[$i] == "a") {
$newVar .= $counter;
$counter++;
}
$newVar .= $var[$i];
}
print $newVar; //1apcdzefg2azbcdr3ajvr
dotJoon
4
Thank you, K. Wolfe. I have your code in the below with your help.
$newVar = "apcdzefgazbcdrajvr";
$counter = 1;
for($i = 0; $i < strlen($var); $i++) {
if($var[$i] == "a") {
$newVar .= $counter;
$counter++;
}
$newVar .= $var[$i];
}
print $newVar;
But the result of it is like the below.
[b]result[/b]
apcdzefgazbcdrajvr
I like to get my target result below instead of the result above.
[b]target result[/b]
[COLOR="#FF0000"]1[/COLOR]apcdzefg[COLOR="#FF0000"]2[/COLOR]azbcdr[COLOR="#FF0000"]3[/COLOR]ajvr
and another:
$var = "apcdzefgazbcdrajvr";
$newVar = '';
$counter = 1;
$token = strtok($var, "a");
while ($token != false):
$newVar .= $counter++ .'a' .$token;
$token = strtok("a");
endwhile;
print $newVar; //1apcdzefg2azbcdr3ajvr
echo '<br /><br />';
dotJoon
6
Thank you, John_Betong.
Your code works fine.