Replacing a character in a string

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
Anarking
Forum Newbie
Posts: 24
Joined: Wed Feb 11, 2009 11:29 am

Replacing a character in a string

Post by Anarking »

Good evening.


I currently have a string that has values that are seperated by '|'

Because of some strange anomalies in a loop sometimes the '|' doubles up to appear as '||' or even '|||'


Is there any way to simply search the string for occurnces of the two and three | and replace them with a single |?



Thanks in advance
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Replacing a character in a string

Post by requinix »

Curious why that's a good idea, but whatever.

Code: Select all

$new = preg_replace('/\|\|+/', '|', $old);
Anarking
Forum Newbie
Posts: 24
Joined: Wed Feb 11, 2009 11:29 am

Re: Replacing a character in a string

Post by Anarking »

That does it, cheerrrs our felllaa
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Replacing a character in a string

Post by Chris Corbyn »

McInfo wrote:Wouldn't it be better to find out why the pipes are doubling up?
Agreed, it's never a good idea to fix a bug by adding ad-hoc code that post-processes to remove the result of the bug. It gets messy very quickly.
Post Reply