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
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

Link to comment
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

 

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

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.