Re: Help with preg_replace

From: Date: Mon, 19 Jan 2004 17:31:28 +0000
Subject: Re: Help with preg_replace
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-175048@lists.php.net to get a copy of this message
Hi I have just realised that I have to delimit the following characters so I can use preg_replace: / ? [ ] Is there any php command to delimit all of these characters as I am getting the string I am trying to replace from the database. eg. \? Any ideas John John Clegg wrote:
Hi Joel, Thanks for the reply. I have tried using "/" to delimit the string and I get the following error String $url = "/http://www.foo.com/maxbid/Unsubscribe.php?EmailAddress=[MAIL]/"; Gives the error: *Warning*: Unknown modifier '/' in* /test.php* on line *8* I found out that I could use ' to delimit from Example 5 in the php manual page for preg_replace. Also I need to replace only one occurance of the string at a time, so I can't use str_replace :-( . Any other suggestions?? Cheers John joel boonstra wrote:
On Mon, Jan 19, 2004 at 06:50:37PM +0200, John Clegg wrote:
Hi I am having some problems with preg_replace and I wondering if someone could suggest a fix or explain why it is not working. Here is the Code: ********************* <?php $code = "blah http://www.foo.com/Unsubscribe.php?EmailAddress=[MAIL] blah"; $url = "'http://www.foo.com/maxbid/Unsubscribe.php?EmailAddress=[MAIL]'"; echo "BEFORE : $code<br><br>"; $replace = "Foo"; $code = preg_replace($url,$replace,$code,1); echo "AFTER: $code<br>"; ?> ********************** Here is the results of the script: ********************** BEFORE : blah http://www.qxlmaxbid.com/maxbid/Unsubscribe.php?EmailAddress=[MAIL] blah AFTER: blah http://www.qxlmaxbid.com/maxbid/Unsubscribe.php?EmailAddress=[MAIL] blah ********************** It should give the following result: ********************** AFTER: blah Foo blah **********************
preg_replace expects the first argument to be a pattern, which should be enclosed in forward slashes ("//"). So your $url variable should be surrounded with slashes. You have single quotes in your $url variable, but I don't think that PHP behaves like perl in letting you use whichever delimiter you choose. Try replacing the single quotes with forward slashes. Additionally, if you're only doing a simple string substitution, you should use str_replace instead: http://php.net/str_replace You won't need the "/" delimiters, and it will be faster than using preg_replace. joel


« previous php.general (#175048) next »