使用 PHP 将空格转换为破折号和小写


Convert spaces to dash and lowercase with PHP

我尝试了一些长方法,但我认为我做错了什么。

这是我的代码

<?php print strtolower($blob); ?>

这使得$blob小写,但另外我需要删除$blob中的任何空格并替换为破折号 ( - )。

我试过这个,但没有用

<?php print (str_replace(' ', '-', $string)strtolower($blob)); ?>

我可以在一行中完成所有这些工作吗?

是的,只需将 strtolower($blob) 的返回值作为 str_replace 的第三个参数传递(您有 $string )。

<?php print (str_replace(' ', '-', strtolower($blob))); ?>

对于字符串换行,您可以使用专用的自动换行函数。

str_replace

str_replace在线文档

<?php
$str = 'Convert spaces to dash and LowerCase with PHP';
echo str_replace(' ', '-', strtolower($str));
// return: convert-spaces-to-dash-and-lowercase-with-php

自动换行

自动换行在线文档

$str = 'Convert spaces to dash and LowerCase with PHP';
echo wordwrap(strtolower($str), 1, '-', 0);
// return: convert-spaces-to-dash-and-lowercase-with-php

在线代码: https://3v4l.org/keWGr

顺便说一句,在WordPress中您可以使用sanitize_title_with_dashes

https://developer.wordpress.org/reference/functions/sanitize_title_with_dashes/