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.
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.
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.
Try str_replace(' ', '-', $string);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With