Page 1 of 1

How to find/replace?

Posted: Sun Jul 27, 2003 3:13 pm
by Fuzzmonkey
Hi, I'm trying to be able to Find and Replace any text on a web page. I've got input fields, etc., but I put the simplified version into a simple PHP page as such:

<? $string = "all the pizza and macaroni and page text in here!";
preg_replace('pizza','macaroni',$string); ?>

but I get the following error:
Warning: Delimiter must not be alphanumeric or backslash in <...>/TestingFindReplace.php on line 2


Also, instead of [<? $string = "all the...here!";] which would require pasting new text in there each time the page is updated, is there an automated way you could just have it search the whole file? Thanks!

Chris

Posted: Sun Jul 27, 2003 3:40 pm
by patrikG
preg_replace uses regular-expressions for the search pattern. So the correct syntax for your code above is

Code: Select all

<?php $string = 'all the pizza and macaroni and page text in here!';
echo preg_replace('/(pizza|macaroni)/','bananas',$string); ?>
This will replace "pizza" or "macaroni" with "bananas" (not case-sensitive).

However, for a simple search like this, you don't need regular expressions (which, due to their complexity, have more overhead). A faster way of doing it is using str_replace.
If you are determined to use regular expressions, read up on them in the manual. There also some nice tutorials out there that give you and idea, one being here.

The way to search an entire file for a particular search-pattern is to load the file in a string. You can do that with this code

Code: Select all

if ($myFile = implode('', file($myPath.$myFilename)))
{
//replacing
$search = array (0=>'pizza',1=>'macaroni');
$myFile=str_replace($search,'bananas',$myFile);
echo $myFile;
}
Note that both the search-pattern as well as the replacement can be arrays (see str_replace in the manual).

Posted: Sun Jul 27, 2003 3:41 pm
by trollll
I think you want to combine the str_replace function, the file_get_contents function and the file_put_contents function to make a search and replace through files script. The str_replace function works with strings rather than regular expressions, which I think gives you that error when you don't use regular expressions with that function.