Page 1 of 1

replacing text in a string..

Posted: Wed Nov 13, 2002 1:25 am
by Shadough
I am trying to filter a string. err.. I thought it could be done this way:

here is my code:

Code: Select all

<?
$string="I dislike ASP.";

$search=array("dislike", "ASP");

$replace=array("like", "PHP");

echo str_replace($search, $replace, $string);
?>
From the manual:
"In PHP 4.0.5 and later, every parameter to str_replace() can be an array."

I am using v4.2.3

It does not work for me. The results:

Parse error: parse error, expecting `')'' in /home/momow3/public_html/f.php on line 4

Cannot? I'm sure I've like that in the past. Help?!

Thanks.

Posted: Wed Nov 13, 2002 1:33 am
by volka
there's no error in the posted script, output is I like PHP. as expected.
Is there something else in your original script?

Posted: Wed Nov 13, 2002 2:51 am
by twigletmac
In your original script you may have forgotten to close the parenthesis around one of the array() statements.

Mac

Posted: Wed Nov 13, 2002 4:12 am
by Shadough
Hi, it works now. I do not understand why it did not work the first time b/c that is the exact and only snippet I was using. One of those php 'ghostys' maybe , heh.

Thanks.

Posted: Wed Nov 13, 2002 4:59 am
by Heavy
Make shure you send headers to prevent proxy or browser caching. Otherwise, you might get confused by pages not appearing as they should (and have database corruption... if you code without database integrity between page-loads and proper use of session vars in mind).

Code: Select all

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");    // Date in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
                                                     // always modified
header("Cache-Control: no-store, no-cache, must-revalidate");  // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");                          // HTTP/1.0

Posted: Wed Nov 13, 2002 10:14 am
by m3mn0n
For replacing, i strongly suggest using eregi_replace().

8) Here is a snipplet from a guest book i made, i enabled Smilies in the guest book by using a simple eregi_replace() function to replace the smilies call with the image to display:

Code: Select all

<?php
$s1 = ":)";
$Replace = "<img src="smile.gif">";
$Arrayї"MessegeBody"] = eregi_replace($s1, $Replace, $Arrayї"MessegeBody"]);
?>

Enjoy~

Posted: Wed Nov 13, 2002 10:17 am
by m3mn0n
lol, i use the same replace image and code as the forums here do so where you see the image in my snipplet, it is accually ":" together with ")"

Posted: Thu Nov 14, 2002 2:13 am
by twigletmac
If you're just doing a straight replace ie, replace this exact text with this other exact text then use str_replace(). If you're replacing needs are more complex, ie. you need to use regular expressions then you'd need to use ereg_replace() or preg_replace().

Mac