Jump to content

[SOLVED] Advanced str_replace


lockdownd7

Recommended Posts

I need a function that works like str_replace, but lets me replace each instance of the string I'm finding with a different value. 

 

Something like this:

str_replace($stringtobereplaced , $array[] , $filebeingsearched);

 

Where the first instance would be replaced by $array[0], the second instance by $array[1], etc.  Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/172629-solved-advanced-str_replace/
Share on other sites

Why not just create a loop with the array and use preg_replace with the replacement limit to 1

here's a basic concept (untested)

$string = 'test test test test test test test test test test ';
$find = '/test/i';
$replace = array('1','2','3','4','5');

foreach($replace as $R)
{
$string = preg_replace($find, $R, $string,1);
}
echo $string;

 

expected output

1 2 3 4 5 test test test test test

Why not just create a loop with the array and use preg_replace with the replacement limit to 1

here's a basic concept (untested)

$string = 'test test test test test test test test test test ';
$find = '/test/i';
$replace = array('1','2','3','4','5');

foreach($replace as $R)
{
$string = preg_replace($find, $R, $string,1);
}
echo $string;

 

expected output

1 2 3 4 5 test test test test test

 

The string I'm replacing is a variable itself... how would I represent that with a regex?

like so

 

$find = "Hello"; //your string

$ifind = preg_quote($find, '/');
//$find = "/$ifind/i"; //case insensitive OR
$ifind = "/$ifind/"; //case sensitive 

$replace = array('1','2','3','4','5');
foreach($replace as $R)
{
   $string = preg_replace($ifind, $R, $string,1);
}
echo $string;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.