简体   繁体   English

PHP str_replace用破折号替换空格,但破折号太多

[英]PHP str_replace replace space with dash, but too many dash

I have this string here photo of the day - 2011 and I need to look like photo-of-the-day-2011 when I do a str_replace, I get this output: 我今天这张photo of the day - 2011 photo-of-the-day-2011当我做一个str_replace时,我需要看起来像photo of the day - 2011 photo-of-the-day-2011 ,我得到这个输出:

photo-of-the-day---2011 what can I do to fix this? photo-of-the-day---2011我该怎么做才能解决这个问题?

Here is the code: 这是代码:

$albumName = 'photo of the day - 2011'; (this comes from a db and cannot change it)
$albumName = str_replace(" ", "-", $albumName);

You can use the more powerful preg_replace , instructing it to replace runs of dashes and/or spaces with a single dash: 您可以使用功能更强大的preg_replace ,指示它用一个破折号替换短划线和/或空格的运行:

$name = preg_replace('/[\s-]+/', '-', $name);

[\\s-]+ is a regular expression that matches "one or more of: whitespace and dashes". [\\s-]+是一个匹配“一个或多个:空格和破折号”的正则表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM