Issue
I have this code and my question is how can I use preg_replace to replace string one by one
$arr = ["{A}","{B}","{C}","{A}"];
$string = "{A}{B}{C}{A}";
foreach ($arr as $item){
$replacement = "<span class=\"c\">{$item}</span>";
$new_String = preg_replace("/$item/",$replacement ,$string);
}
the result is this :
<span class="c">
<span class="c">{A}</span>
</span>
<span class="c">{B}</span>
<span class="c">{C}</span>
<span class="c">
<span class="c">{A}</span>
</span>
Because I have 2 {A} in my string preg_replace make 2 span for both of the {A} . how to fix this ?
Solution
In addition to Casimir's suggested snippets, you can also use this one:
Code: (Demo)
$arr = ["{A}", "{B}", "{C}", "{A}"];
$start = '<span class="c">';
$end = '</span>';
$string = "{A}{B}{C}{A}";
foreach (array_unique($arr) as $item) {
$string = str_replace($item, $start . $item . $end, $string);
}
echo $string;
It alters how you define the replacement, but avoids regex.
As a more robust, solution (if your project requires it), using strtr()
is ideal for multiple replacements on the same string because it avoid replacing a replacement. As you can see in Casimir's answer, there's a bit of preparation required.
Here's a language-construct version of the Casimir's technique: (Demo)
$arr = ["{A}", "{B}", "{C}", "{A}"];
foreach (array_unique($arr) as $item) {
$translator[$item] = '<span class="c">' . $item . '</span>';
}
var_export($translator);
echo "\n\n---\n\n";
$string = "{A}{B}{C}{A}";
echo strtr($string, $translator);
Output:
array (
'{A}' => '<span class="c">{A}</span>',
'{B}' => '<span class="c">{B}</span>',
'{C}' => '<span class="c">{C}</span>',
)
---
<span class="c">{A}</span><span class="c">{B}</span><span class="c">{C}</span><span class="c">{A}</span>
Answered By - mickmackusa Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.