Better "String Cleaning" Function?

Discussion in 'PHP' started by proph3t, Apr 5, 2006.

  1. #1
    I have this simple function:

    
    function strip_url($title)
    {
            return preg_replace('/-+/i', '-', strtolower(implode('-', preg_replace('/[^a-z0-9]/i', '', explode(' ', $title)))));
    }
    
    PHP:
    I use it to generate a clean url compatible string out of any string inputted and it works very very well.

    There is one problem though, if a user inputs special characters they can "break" it and have it return just blankness. For example, passing "````" without the quotes returns nothing. I am trying to come up with a better solution for this and so Im asking DP for some ideas.
     
    proph3t, Apr 5, 2006 IP
  2. Dejavu

    Dejavu Peon

    Messages:
    916
    Likes Received:
    53
    Best Answers:
    0
    Trophy Points:
    0
    #2
    how about just urlencode($title) ?
    or did I misunderstand something?
     
    Dejavu, Apr 5, 2006 IP
  3. proph3t

    proph3t Guest

    Messages:
    145
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    urlencode() is nice but I wanted something different. But, thanks for that it gave me some ideas.
     
    proph3t, Apr 5, 2006 IP
  4. sketch

    sketch Well-Known Member

    Messages:
    898
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    148
    #4
    From what you wrote it sounds like urlencode does exactly what you're trying to do. What're you trying to do that's different?
     
    sketch, Apr 5, 2006 IP
  5. proph3t

    proph3t Guest

    Messages:
    145
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Well I realized that it would be easier to start the function with urlencode and then change it in a few ways to be more SEO optimized, which I have done.
     
    proph3t, Apr 6, 2006 IP
  6. hansi

    hansi Peon

    Messages:
    129
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #6
    You are looking for something like thsi?

    
    <?php
    function replace($x) {
      $k1=array('ä','ö','ü','Ä','Ö','Ü',' ',':','&','?','!','"');
      $k2=array('ae','oe','ue','ae','oe','ue','-','-','und','','','');
      for ($i='0';$i<'12';$i++) {
        $x = str_replace($k1[$i],$k2[$i],$x);
      }
    return $x;
    }
    $clean_title = replace($mytitel);
    ?>
    
    PHP:
     
    hansi, Apr 6, 2006 IP