将文本转换为破折号分隔的单词

Convert text to dash-separated-words

我有一个字符串 "Christmas Spl - Monthly" ,我想将此字符串替换为 "Christmas-Spl-Monthly" 我知道它可能是 str_replace(" ","-", $string); 但在这个字符串中如果我将应用相同的东西那么结果就像:Christmas-Spl---Monthly,我希望如果字符串存在那么 space 在这些词和休息之间应该替换单词

我想要最终答案 "Christmas-Spl-Monthly"

提前致谢

最简单的方法是使用 str_replace 两次。 先把-换成</code>再把<code>换成-

str_replace(" ","-", str_replace(" - "," ", $string));

所以内部 str_replace 给你 Christmas Spl Monthly 和外部 Christmas-Spl-Monthly

解决方案:

这仅适用于破折号 (-)

    $text = preg_replace("/[-]+/i", "-", str_replace(" ","-", "Christmas Spl - Monthly"));
    echo $text;

如果你想多破折号space也转换成单破折号也试试这个

$text = preg_replace("/[- ]+/i", "-",  "Christmas Spl -  Monthly");
echo $text;

我建议先从字符串中删除连字符

$string = "Christmas Spl - Monthly";
$string = str_replace(" -", "", $string);
$string = str_replace(" ", "-", $string);

我先删除了带额外 space 的连字符,然后用连字符替换了 space。所需的输出将是。

// Christmas-Spl-Monthly

使用正则表达式。找到所有单词,然后将它们粘在一起。

$string = 'Christmas Spl - - Monthly';

$matches = [];
preg_match_all('/(\w+)/', $string, $matches);
$new = implode('-', $matches[1]);

echo $new;

Christmas-Spl-Monthly

函数 dashedName()

我有一个函数可以用来生成 ID。

function dashedName($s) {
    $s = preg_replace("/\W+/","-",$s);
    $s = trim($s,"-");
    return $s;
}

这也将非单词字符替换为破折号,使输入字符串 "id-safe"。它还会删除字符串末尾的杂散破折号,因此您不会得到结果 -like-this-.

旁注:此实现比接受的答案快很多(~3 倍)。