homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Regex replacing double dashes problem with underscore plus.
JAB Creations

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

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)

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

[<stuff>] creates a character class. What that means is it matches a single character, among essentially a list of characters. For instance, [A-Z] 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
/--+/ or /[-]{2,}/ to match two or more dashes.

 6:56 pm on May 12, 2011 (gmt 0)


Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved