1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Regular Expression Problem

Discussion in 'PHP' started by Silver89, Mar 8, 2009.

  1. #1
    Hi,

    I have a function to change my urls to seo urls however It's changing:

    - to nothing.

    I want it to keep the dash unchanged, what's preventing this?

    	return str_replace(' ', '-', preg_replace('/([^a-z0-9\s]+)/i', '', trim($text)));
    PHP:

     
    Silver89, Mar 8, 2009 IP
  2. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #2
    In your preg_replace you don't include the hyphen as one of the allowed characters. You only allow letters, numbers, and whitespace.
     
    SmallPotatoes, Mar 9, 2009 IP
  3. Silver89

    Silver89 Notable Member

    Messages:
    2,243
    Likes Received:
    72
    Best Answers:
    0
    Trophy Points:
    205
    #3
    How would I allow hyphens aswel?
     
    Silver89, Mar 9, 2009 IP
  4. buldozerceto

    buldozerceto Active Member

    Messages:
    1,137
    Likes Received:
    43
    Best Answers:
    0
    Trophy Points:
    88
    #4
    This part: /([^a-z0-9\s]+)/i
    replaces any text and number. space with nothing. Thats the problem.
     
    buldozerceto, Mar 9, 2009 IP
    Silver89 likes this.
  5. nabil_kadimi

    nabil_kadimi Well-Known Member

    Messages:
    1,065
    Likes Received:
    69
    Best Answers:
    0
    Trophy Points:
    195
    #5
    Try this:
    return preg_replace('/([^a-z0-9-]+)/i', '', trim(str_replace(' ','-',$text))));
    PHP:
    It:
    * Trims
    * replaces spaces by -
    * deletes all non alphanumeric charactars but leaves -

    I didn't run the script so please correct errors
     
    nabil_kadimi, Mar 9, 2009 IP
    Silver89 likes this.
  6. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Actually it does the opposite; see the ^ character near the beginning.

    Nabil's solution is closer but it will result in unsightly runs of hyphens in some cases.

    I didn't want to spoon feed, but try this:

    return str_replace(' ', '-', trim(preg_replace('/[^a-z0-9]+/i', ' ', $text)));
    Code (markup):
     
    SmallPotatoes, Mar 9, 2009 IP