Page 1 of 1

preg_replace question

Posted: Mon Oct 04, 2004 4:48 pm
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!

Posted: Mon Oct 04, 2004 5:18 pm
by feyd

Code: Select all

preg_replace('#[& ]#','-',$text);

Posted: Mon Oct 04, 2004 5:32 pm
by poster
$text = "Rats & Dogs";
It evaluates to this: "Rats--amp;-Dogs"

Posted: Mon Oct 04, 2004 6:09 pm
by feyd
you can add the expansion yourself.

Posted: Mon Oct 04, 2004 6:36 pm
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

Posted: Mon Oct 04, 2004 8:54 pm
by feyd
[php_man]html_entity_decode[/php_man]()

Posted: Tue Oct 05, 2004 12:58 am
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.

Posted: Tue Oct 05, 2004 2:52 am
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