Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 需要稍微修改一下功能_Php_Regex_Slug - Fatal编程技术网

Php 需要稍微修改一下功能

Php 需要稍微修改一下功能,php,regex,slug,Php,Regex,Slug,我正在写一个自定义的博客脚本,其中的一部分是使用slug作为post URL。到目前为止,我的代码是 public function get_slug($str) { // convert to lowercase $str = strtolower($str); // remove special chars $str = preg_replace('/[^a-zA-Z0-9]/i', ' ', $str); // remove what space f

我正在写一个自定义的博客脚本,其中的一部分是使用slug作为post URL。到目前为止,我的代码是

public function get_slug($str) {
    // convert to lowercase
    $str = strtolower($str);
    // remove special chars
    $str = preg_replace('/[^a-zA-Z0-9]/i', ' ', $str);
    // remove what space from beginning and end
    $str = trim($str);
    // remove repeat spaces
    $str = preg_replace('/\s+/', ' ', $str);
    // replace spaces with hyphens
    $str = preg_replace('/\s+/', '-', $str);

    return $str;
}

这对大多数部分都很有用,但是我注意到,如果单词中间有一个特殊字符,它就用一个连字符改为“不能”,而不是“不能”< /P>。 在预设状态下,我只需编辑数据库并手动修复,我希望它能自动从单词中间去掉特殊字符,而不是用催眠代替它们。

尝试更改:

$str = preg_replace('/[^a-zA-Z0-9]/i', ' ', $str);
致:


这不会将空间放在您不想要的地方,而是允许已经存在的空间停留(目前)。这样你就不会在单词的中间有空格了。(我还从正则表达式中取出了
A-Z
,因为它是不必要的,因为字符串已经是小写的,而且您还使用了
I
修饰符,使其不区分大小写)。

您正在替换
这里:

$str = preg_replace('/[^a-zA-Z0-9]/i', ' ', $str);
把这个放在上面的前面:

$str = preg_replace("/'/i", '', $str);

请作为此项的潜在替代品进行检查。尝试在第一次替换时将空格更改为空字符串。感谢@John,他对PHP还是新手,对regex也是非常陌生的,他从教程中获得了此信息。
$str = preg_replace("/'/i", '', $str);