gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:11:58 24 4
gpt4 key购买 nike

我这里有这个字符串 photo of the day - 2011 并且我需要在执行 str_replace 时看起来像 photo-of-the-day-2011,我得到这个输出:

今日照片---2011 我该怎么做才能解决这个问题?

代码如下:

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

最佳答案

你可以使用更强大的preg_replace ,指示它用单个破折号替换连续的破折号和/或空格:

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

[\s-]+regular expression匹配“一个或多个:空格和破折号”。

关于PHP str_replace 用破折号替换空格,但破折号太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com