Replace Spaces with Hyphens using PHP

Discussion in 'Site & Server Administration' started by amitash, Dec 19, 2009.

  1. #1
    Hello Guys,
    I have a problem here. Im using the following PHP code to retrieve data from my MySQL database. In the echo you can see the url to which the data is hyper-linked using the <a> tags. The {$row['tag']} is the main part of the URL. But it has spaces. How can i replace these spaces into hyphens.

    <?php 
    $query = "SELECT tag FROM dle_search ORDER BY id DESC limit 0, 30";
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    echo "<a href='http://www.techspott.com/search/{$row['tag']}.html'>{$row['tag']}</a> | ";
    } 
    ?>
    PHP:
    For example, the output looks like this:
    <a href="http://www.mydomain.com/search/Some Text Here.html">Some Text Here</a>

    I have already created an .htaccess file to redirect these to respective pages. If someone can help, i could replace these spaces with hyphens
     
    amitash, Dec 19, 2009 IP
  2. tolra

    tolra Active Member

    Messages:
    515
    Likes Received:
    36
    Best Answers:
    1
    Trophy Points:
    80
    #2
    <?php 
    $query = "SELECT tag FROM dle_search ORDER BY id DESC limit 0, 30";
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result, MYSQL_ASSOC))
    {
    echo "<a href='http://www.techspott.com/search/" . str_replace(' ', '-', $row['tag']) . ".html'>{$row['tag']}</a> | ";
    } 
    ?>
    PHP:
     
    tolra, Dec 19, 2009 IP
  3. amitash

    amitash Well-Known Member

    Messages:
    399
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    125
    #3
    Thanks Man! This Helped. A problem though! When i enter http://www.techspott.com/search/Google-Talk.html, the site searches for Google-Talk. Even though the URL is with a hypen, when it searches, it should search for Google Talk. Otherwise "no result found" error occurs.
     
    amitash, Dec 19, 2009 IP
  4. tolra

    tolra Active Member

    Messages:
    515
    Likes Received:
    36
    Best Answers:
    1
    Trophy Points:
    80
    #4
    You need to convert the - back to a space in the PHP before it is sent to the search function.

    str_replace('-', ' ', $someVariable);

    Can't give you any more than that without seeing the offending code.
     
    tolra, Dec 19, 2009 IP
  5. amitash

    amitash Well-Known Member

    Messages:
    399
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    125
    #5
    Thanks. I just had to change it in the search.php file which did all the search activity.
     
    amitash, Dec 19, 2009 IP
  6. YottaCash

    YottaCash Guest

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    thanks, realli useful.
     
    YottaCash, Dec 19, 2009 IP