0

I have a text like this,

$string = "I have some fruits like [name], [another_name] and [one_another_name]";

And an array like this,

$fruits_array = array("Banana", "Apple", "Orange");

Now, how can I replace the texts between braces by following array?

I want a result like this,

I have some fruits like Banana, Apple and Orange.

Please provide the actual solution.

Thanks in advance.

Teenager
  • 23
  • 6

5 Answers5

3

Try this

$string = "I have some fruits like [name], [another_name] and [one_another_name]";
$fruits_array = array("Banana", "Apple", "Orange");

foreach($fruits_array as $replace)
{
    $string = preg_replace('/\[.*?\]/i', $replace, $string, 1);
}

echo $string;
1
<?php

$string = "I have some fruits like [name], [name] and [name]";

$fruits_array = array("Banana", "Apple", "Orange");

foreach ($fruits_array as $key => $value) {
  $string = preg_replace('[name]', $value, $string, 1);
}
$string = str_replace('[', '', $string);
$string = str_replace(']', '', $string);
echo $string;
Viswanath Polaki
  • 1,357
  • 1
  • 10
  • 19
0

Implode the array by comma with space. Try like this :

$fruits_array = array("Banana", "Apple", "Orange");

echo 'I have some fruits like '.implode(', ',$fruits_array).'.';
0

Try this...

$string = "I have some fruits like [name], [name] and [name]";
$arr = explode('[name]',$string);
$fruits_array = array("Banana", "Apple", "Orange");

$newText = '';
for($i = 0; $i < count($arr); $i++){
   $newText .= $arr[$i] . $fruits_array[$i];
}

echo $newText;
Ranga Lakshitha
  • 286
  • 2
  • 14
0

You might also use preg_replace_callback with a regex \[[^]]+\] to match an opening [, then match not a ] using a negated character class and then match ].

In the callback use array_shift to shift an element off the beginning of the array and use that as the replacement.

$string = "I have some fruits like [name], [another_name] and [one_another_name]";
$fruits_array = array("Banana", "Apple", "Orange");

$string = preg_replace_callback(
    '/\[[^]]+\]/',
    function ($matches) use (&$fruits_array) {
        return array_shift($fruits_array);
    },
    $string
);

echo $string;

Demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70