str_replace or preg_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
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

str_replace or preg_replace?

Post by thiscatis »

Hi guys,

I'm having some troubles here...


I'm checking an URL to see if it contains '&number=1' where '1' is a variable.
(I'm doing this with isset)

and if the URL contains that string with the variable number at the end it should remove the entire string.
I've managed to do this with a constant string with the str_replace() function. But I can't manage to find
a way to remove the bit if it contains a variable number at the end...

Any suggestions?

Thanks in advance!


thiscatis
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: str_replace or preg_replace?

Post by s.dot »

Yeah, preg_replace(). \d will check for a number
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Re: str_replace or preg_replace?

Post by thiscatis »

$this_safe_page = preg_replace('&number=/[\d]/', '', $this_page);


gives me this:

Warning: preg_replace() [function.preg-replace]: No ending delimiter '&' found in ...

:banghead:
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: str_replace or preg_replace?

Post by John Cartwright »

Because you need to specify the delimers ;)
preg_replace(#'&number=/[\d]/#', '', $this_page);
.. which can be any character (which have to be at the front and end of the pattern)
thiscatis
Forum Contributor
Posts: 434
Joined: Thu Jul 20, 2006 11:00 am

Re: str_replace or preg_replace?

Post by thiscatis »

Edit,

Code: Select all

$this_safe_page = preg_replace('/\&number=\d/', '', $this_page);
this did the trick
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: str_replace or preg_replace?

Post by Chris Corbyn »

If there will ever be more than one digit in the number add a + sign:

Code: Select all

'/&number=\d+/'
EDIT | The ampersand doesn't need escaping since it has no special meaning to the regular expression engine ;)
Post Reply