PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] how to replace string with another one by one with preg_replace

 November 20, 2022     php, preg-replace, regex     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing