How to find/replace?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Fuzzmonkey
Forum Newbie
Posts: 1
Joined: Sun Jul 27, 2003 3:13 pm

How to find/replace?

Post 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
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post 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).
Last edited by patrikG on Sun Jul 27, 2003 3:42 pm, edited 1 time in total.
User avatar
trollll
Forum Contributor
Posts: 181
Joined: Tue Jun 10, 2003 11:56 pm
Location: Round Rock, TX
Contact:

Post 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.
Post Reply