Removing different sets of characters 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
psionic98
Forum Newbie
Posts: 2
Joined: Thu Aug 20, 2009 3:47 pm

Removing different sets of characters in a string

Post by psionic98 »

Hi all, I'm new to php coding and have a question.

I have a database that has some fields which contain our version of color codes. The codes are as follow:
&G=bright green
&g=dark green
&n=new line
&R=bright red
&r=dark red

and so on and so on through the normal spectrum.

my problem is trying to remove those codes from the string before printing it out.

I've looked at explode/preg_replace, but cant seem to iron this out.. an example of a string would be:

&GI jumped &Yover &Gthe fence&n

I need it to print out as "I jumped over the fence" without the quotes obviously!

Any help is appreciated... I was thinking to put all of the color codes into an array, but I don't know how to go about checking against the array to remove the code.

Thanks

stan
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: Removing different sets of characters in a string

Post by cpetercarter »

Something like this, perhaps:

Code: Select all

$codes = array('&r', '&g', '&b', '&y');
 
foreach ($codes as $code)  {
$text = str_replace($code,"",$text);
}
 
User avatar
jackpf
DevNet Resident
Posts: 2119
Joined: Sun Feb 15, 2009 7:22 pm
Location: Ipswich, UK

Re: Removing different sets of characters in a string

Post by jackpf »

You don't need the foreach loop since str_replace() accepts arrays as parameters.
psionic98
Forum Newbie
Posts: 2
Joined: Thu Aug 20, 2009 3:47 pm

Re: Removing different sets of characters in a string

Post by psionic98 »

worked great and didnt need the for loop.. thanks a bunch
Post Reply