preg_replace question

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
poster
Forum Newbie
Posts: 3
Joined: Mon Oct 04, 2004 4:46 pm

preg_replace question

Post by poster »

If I wanted to use preg replace to replace an occurence of " & " with "-" and a space with "-" any idea what the function should look like?

Example: my string: "Rats & Dogs", I want to convert it to "Rats-Dogs"
and if the string is "Rats Dogs", I want it to be "Rats-Dogs"

Thanks!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

preg_replace('#[& ]#','-',$text);
poster
Forum Newbie
Posts: 3
Joined: Mon Oct 04, 2004 4:46 pm

Post by poster »

$text = "Rats & Dogs";
It evaluates to this: "Rats--amp;-Dogs"
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

you can add the expansion yourself.
poster
Forum Newbie
Posts: 3
Joined: Mon Oct 04, 2004 4:46 pm

Post by poster »

feyd wrote:you can add the expansion yourself.
How would I do that? This is the problem I am having, I can't get rid of that & in the string
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

[php_man]html_entity_decode[/php_man]()
User avatar
vigge89
Forum Regular
Posts: 875
Joined: Wed Jul 30, 2003 3:29 am
Location: Sweden

Post by vigge89 »

I think you're doing a htmlentities() on the string before you replace this. Either use html_entity_decode() as Feyd said, or move the htmlentities() call below the preg_replace() call.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Instead of preg_replace() you could use [php_man]str_replace[/php_man]() it should be a bit more efficient for a simple replacement like this:

Code: Select all

$converted_text = str_replace(array('&', ' '), '-', $text);
Mac
Post Reply