24

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.

Robdogga55
  • 309
  • 1
  • 4
  • 12
  • It's quite obvious you now have spaces since you put them there yourself with: `str_replace(array(':', '\\', '/', '*'), ' ', urldecode($row_getDisplay['title']));`. Replace it with "nothing", e.g.: `str_replace('yourChar', '', 'yourString');`. After that you can replace the remaining spaces with dashes. – Jules Jan 30 '13 at 10:11

2 Answers2

52

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

ka_lin
  • 9,329
  • 6
  • 35
  • 56
  • 3
    simplest solution, you can add array of invalid characters like str_replace(array(" ", ";"), array("-", "_"), $str) –  Jan 30 '13 at 10:16
  • Am I the worst for overlooking any preg_replace solution when there are more straight and simpler options? Like yours? Am I missing something? – LizardKG Aug 13 '20 at 08:34
27

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

  • Thanks I will try that in a minute, how would I include the generec function into my code, – Robdogga55 Jan 30 '13 at 10:11
  • 3
    Put it in a file (eg "helpers.php") and include it in your code at the beginning of file with before you call the function. This way you can reuse it in multiple files without having to type out or declare the function in each file. – Christopher Brunsdon Jan 31 '13 at 08:37
  • So just put it in a file 'helpers.php' include the page in the code and that's it? – Robdogga55 Jan 31 '13 at 12:42