php 用 URL 中的破折号替换空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14600639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:36:45  来源:igfitidea点击:

Replace spaces with a dash in a URL

phpurl-rewriting

提问by Robdogga55

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

我设法替换了特殊字符,例如 : ; / etc 在我的 URL 中,但现在它又有空格了。这是我的代码:

<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.

我希望它喜欢它删除特殊字符以及用破折号替换空格。

回答by ka_lin

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

尝试 str_replace(' ', '-', $string);

回答by Christopher Brunsdon

You can use preg_replace:

您可以使用 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

编辑:这是我去年用来使我的 URL 整洁的generec 函数

    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

它将所有非字母数字字符转换为空格,然后将所有空格转换为破折号,然后修剪字符串末尾/开头的任何破折号。这比必须在 str_replace 中列出特殊字符更有效