Jump to content

problem with str_replace array


darkfact

Recommended Posts

The first two work perfectly.  In the third, I tried to put  them together in an array and nothing happens.  Can anyone see what I am doing wrong?

 

Thanks

 

 

<?php $ident = $_POST['ident']; ?>
<?php
$filename = 'r5include.html'; 
$string = file_get_contents($filename); 
$data = str_replace("add.html' target='_blank'","$ident.html' target='iframe2'","$string");
$handle = fopen($filename, "w+"); 
fwrite($handle,$data); 
fclose($handle); 
?>

<?php $ident = $_POST['ident']; ?>
<?php
$ident2 = ($ident . 2);
$filename = 'r5include.html'; 
$string = file_get_contents($filename); 
$data = str_replace("'images/up.jpg'","'$ident/$ident2.jpg'","$string");
$handle = fopen($filename, "w+"); 
fwrite($handle,$data); 
fclose($handle); 
?>

<?php $ident = $_POST['ident']; ?>
<?php
$ident2 = ($ident . 2);
$filename = 'r5include.html'; 
$string = file_get_contents($filename); 
$old = array("'images/up.jpg'","add.html' target='_blank'");
$new = array("'$ident/$ident2.jpg'","$ident.html' target='iframe2'");
$data = str_replace("$old","$new","$string");
$handle = fopen($filename, "w+"); 
fwrite($handle,$data); 
fclose($handle); 
?>

Link to comment
https://forums.phpfreaks.com/topic/215963-problem-with-str_replace-array/
Share on other sites

I don't think it works quite like that. From the manual.

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

 

I'm pretty sure you'd have to do each of the three separately in your 3rd example.

 

Thanks for the reply, this is the entire r5include file:

 

<img height=75 src='images/up.jpg' 
hidefocus='true' usemap='#record51' />
<map name='record51'>
  <area shape='rect' coords='0,0,75,75' 
href='add.html' target='_blank'>

 

If I use either of the first two that I posted it changes the way i want it to.  If I put them both on the same page separately it changes the whole thing to what I want.  But the one where I put them in an array doesn't do anything.

This line is incorrect:

$data = str_replace("$old","$new","$string");

By enclosing $old and $new in quotes, you are forcing PHP to convert the arrays to strings, which will be the word "array".

 

It is not necessary, and in fact sometimes hurtful, to enclose a variable in quotes when assigning it or passing it to a function.  Change the line to:

$data = str_replace($old, $new, $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.