Need some help with str_replace and preg_match

Discussion in 'PHP' started by Philopoemen, Dec 10, 2007.

  1. #1
    Hi all,


    I am very bad with string functions, so I was wondering if any of you have the following function.

    Here is what I want it to do:

    1. It takes a string, not very long, usually 32-64 characters.
    2. It removes all characters, except [a-z] [0-9].
    3. It replaces all white space between words with "-".

    So if it takes a string like: "Ce credeti despre acest film???", it will return: "ce-credeti-despre-acest-film".


    Help is appreciated :)
     
    Philopoemen, Dec 10, 2007 IP
  2. matthewrobertbell

    matthewrobertbell Peon

    Messages:
    781
    Likes Received:
    35
    Best Answers:
    0
    Trophy Points:
    0
    #2
    $string = preg_replace('/[^0-9a-z]/', '', str_replace(' ', '-', strtolower($string)));
    PHP:
    Should work?
     
    matthewrobertbell, Dec 10, 2007 IP
    Philopoemen likes this.
  3. Philopoemen

    Philopoemen Peon

    Messages:
    704
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks!
    It did not work properly, so I did some minor changes
    $string = preg_replace('/[^\-0-9a-z]/', '', str_replace(' ', '-', strtolower($string)));
    PHP:
    P.S. i would however like it to check if there is just 1 space between words, and if it's more than just 1, trip it to 1 space.
     
    Philopoemen, Dec 10, 2007 IP
  4. Paul Starsky

    Paul Starsky Peon

    Messages:
    10
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Then you need to modify it a bit:

    
    $string = preg_replace('/[^\-0-9a-z]/', '', preg_replace('/\s+/', '-', strtolower($string)));
    PHP:
     
    Paul Starsky, Dec 10, 2007 IP