Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Regex replacing double dashes problem with underscore plus.

10:04 pm on May 11, 2011 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member jab_creations is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Aug 26, 2004
posts: 3168
votes: 22

I have the string "Hello_+ Wo--rld" which I'm trying to replace double dashes however when an instance of "_+" is encountered it replaces it with two dashes. If I remove the plus sign from $d then it won't replace double dashes with single dashes. The only work-around I've been able to get to work is using a second $d regular expression however I'd really like to avoid that. Suggestions please?

- John

$a = strtolower(Hello_+ Wo--rld");

$b = str_ireplace('_','-',$a);

$c = str_ireplace(' ','-',$b);

$d = preg_replace('/[--]+/','-',$c);

$e = preg_replace('/[^a-z0-9-]/','',$d);

$f = trim($e,'-');

echo $f;
3:37 pm on May 12, 2011 (gmt 0)

Junior Member

10+ Year Member

joined:Jan 28, 2006
votes: 0

$d = preg_replace('/[--]+/','-',$c);
doesn't do what you think it does.

creates a character class. What that means is it matches a single character, among essentially a list of characters. For instance,
matches any character between A and Z.
doesn't match two consecutive dashes, it matches a dash. So
is equivalent to
, which matches one or more dashes.

You want something more like
to match two or more dashes.
6:56 pm on May 12, 2011 (gmt 0)


WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:July 31, 2003
votes: 2


Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members