Welcome to WebmasterWorld Guest from 54.196.238.210

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Regex replacing double dashes problem with underscore plus.

     

JAB Creations

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

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



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

<?php
$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;
?>

pinterface

3:37 pm on May 12, 2011 (gmt 0)

5+ Year Member



$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.

coopster

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

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



Example:
[webmasterworld.com...]
 

Featured Threads

Hot Threads This Week

Hot Threads This Month