Removing Space from the URL

Discussion in 'PHP' started by phantomddl, Oct 3, 2007.

  1. #1
    i read some tutorials but couldn't get it worked so i need help now. here is the code i use:

    <?php
        $conn = mysql_connect("localhost", ****, ****);
        mysql_select_db($DB);
        $sql = mysql_query("SELECT * FROM ***** ORDER BY rand() LIMIT 0,50");
        while($result = mysql_fetch_array($sql)) {
        echo "<a href=/search/0/".$result["search_id"] . "-" .$result[search] . ".html>" .$result["search"] . "</a> ";
        }
    ?>
    PHP:
    this way it shows the search url with space in it, i want to replace it with "-"
    i know i must use str_replace but where and how, it confused me
    can any of you help me?
     
    phantomddl, Oct 3, 2007 IP
  2. pixel_boost

    pixel_boost Peon

    Messages:
    55
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Instead of your while put this one:
    
    while($result = mysql_fetch_array($sql)) {
        $search = preg_replace('/\s/', '-', $result[search]); 
        echo "<a href=/search/0/".$result["search_id"] . "-" .$search . ".html>" .$result["search"] . "</a> ";
    }
    PHP:
     
    pixel_boost, Oct 3, 2007 IP
    phantomddl likes this.
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    Don't use preg_replace unless you have a reason to, because it's slower than str_replace. To make it any useful, you could just add a plus sign after the \s to make it replace multiple spaces with just one dash.
     
    nico_swd, Oct 3, 2007 IP
  4. phantomddl

    phantomddl Well-Known Member

    Messages:
    2,856
    Likes Received:
    30
    Best Answers:
    0
    Trophy Points:
    160
    Articles:
    15
    #4
    thanks to both. rep added. and yes it works :p

    edit: couldn't add + rep to you nico, sorry
     
    phantomddl, Oct 3, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    No worries. :) The intention is what counts, hehe.
     
    nico_swd, Oct 3, 2007 IP
  6. pixel_boost

    pixel_boost Peon

    Messages:
    55
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #6
    well i hope that u urlencode everything that is left after you strip that url.
    Or maybe you should strip anything that is not letter or digit ? ( smth like:
     preg_replace('/[^a-zA-Z0-9\-]/', '-', $result[search]); 
    PHP:
    Good luck.
     
    pixel_boost, Oct 4, 2007 IP