PHP preg替换干净的url

时间:2017-06-12 04:55:06

标签: php regex preg-replace

这次替换的最佳解决方案是什么? 快速优化

我的链接:

https://example.com/event/123/Kinda Don't Care2 Feat. Jaba/Country Music (1990)

我想要干净:

https://example.com/event/123/Kinda-Dont-Care2-Feat-Jaba/Country-Music-1990

preg_replace('???????', '-', $strUrl);

修改

$str1 = "Kinda Don't Care2 Feat. Jaba";

$str2 = "Country Music (1990)";

替换为:

$str1 = "Kinda-Dont-Care2-Feat-Jaba";

$str2 = "Country-Music-1990";

感谢。

1 个答案:

答案 0 :(得分:1)

试试这个

$string = "example.com/event/123/Kinda Don't Care2 Feat. Jaba/Country Music (1990)";

    // remove all non alphanumeric characters except spaces
    $clean =  preg_replace('/[^a-zA-Z0-9\s]/', '', strtolower($html)); 

    // replace one or multiple spaces into single dash (-)
    $clean =  preg_replace('!\s+!', '-', $clean); 

    echo $clean;

ref- Automatic clean and SEO friendly URL (slugs)