Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace spaces with a dash in a URL

Tags:

I managed to replace special characters such as : ; / etc in my URL but now it has the spaces again. Here is my code:

<h3><a href="<?php echo (isset($row_getDisplay['post_id']) ? $row_getDisplay['post_id'] : ''); ?>_<?php echo str_replace(array(':', '\\', '/', '*'), ' ', urldecode($row_getDisplay['title'])); ?>.html" ><?php echo (isset($row_getDisplay['title']) ? $row_getDisplay['title'] : ''); ?></a></h3> 

I want it to like it is remove special characters as well as replace spaces with dashes.

like image 838
Robdogga55 Avatar asked Jan 30 '13 09:01

Robdogga55


People also ask

How do you replace spaces with dashes?

Use the replace() method to replace spaces with dashes in a string, e.g. str. replace(/\s+/g, '-') . The replace method will return a new string, where each space is replaced by a dash.

How do you replace a space in react?

In the above code, we have passed two arguments to the replace() method first one is regex /\s/g and the second one is replacement value + , so that the replace() method will replace all-white spaces with a + sign. The regex /\s/g helps us to remove the all-white space in the string.


2 Answers

Try str_replace(' ', '-', $string);

like image 84
ka_lin Avatar answered Oct 12 '22 11:10

ka_lin


You can use preg_replace:

preg_replace('/[[:space:]]+/', '-', $subject); 

This will replace all instances of space with a single '-' dash. So if you have a double, triple, etc space, then it will still give you one dash.

EDIT: this is a generec function I've used for the last year to make my URLs tidy

    function formatUrl($str, $sep='-')     {             $res = strtolower($str);             $res = preg_replace('/[^[:alnum:]]/', ' ', $res);             $res = preg_replace('/[[:space:]]+/', $sep, $res);             return trim($res, $sep);     } 

It will convert all non-alphanumeric characters to space, then convert all space to dash, then trim any dashes on the end / beginning of the string. This will work better than having to list special characters in your str_replace

like image 42
Christopher Brunsdon Avatar answered Oct 12 '22 09:10

Christopher Brunsdon