Home > Blockchain >  How to replace a single string with an array?
How to replace a single string with an array?

Time:03-19

I have a string ..... one .... and I have an array that contains images link

$my_string = '..... one ....';

$images = [
  "0" => "image_url_1",
  "1" => "image_url_2",
]

I need to replace the word one with these two images

my code:


$pdf_form = ".... <span>one</span> ....";

foreach ($images as $image) {
    $pdf_form = Str::replace('one', '<img src="' . $image . '" />', $pdf_form);
}

dd($pdf_form);

The output is, I got just the first image only!

How can I print both images?

CodePudding user response:

Do it like this

$replace_string=""; 
foreach ($images as $image) {
$replace_string.='<img src="' . $image . '" />';
}
 $pdf_form = Str::replace('one', $replace_string, $my_string);

CodePudding user response:

I see only twos bugs. 1) You use declare $image but never used. Change this: foreach ($images as $image) {to foreach ($images as $value) {

  1. In a loop you will always override the value if you asign the value o variable by using =. Change this to .=

Update

$pdf_form .= \Stthis line is in your code wrong. You assign with = but you have to concat the strings with .=

        $pdf_form = ".... <span>one</span> ....";
        $images = ['pic1.png', 'pic2.png'];
        foreach ($images as $image) {
            $pdf_form .= \Str::replace('one', '<img src="' . $image . '" />', $pdf_form);
        }

        dd($pdf_form);

output ^ ".... <span>one</span> ........ <span><img src="pic1.png" /></span> ........ <span><img src="pic2.png" /></span> ........ <span><img src="pic1.png" /></span> .... ◀"

CodePudding user response:

Take a look at the strtr function.

If I understand your question correctly, you want to display both images each with their own <img> tag.

$my_string = '<img src="one" />';

$images = [
  "0" => "image_url_1",
  "1" => "image_url_2",
]

$pdf_form = '';

foreach ($images as $image) {
    $pdf_form = $pdf_form . strtr($my_string, ['one' => $image]);
}
  • Related