将文本转换为破折号[关闭]

问题描述 投票:0回答:5

我有一个字符串“ Christmas Spl-Monthly”,我想将此字符串替换为“ Christmas-Spl-Monthly”我知道这可能是str_replace(" ","-", $string);,但是如果我将应用相同的内容,则在此字符串中,结果将是:Christmas-Spl---Monthly,我希望如果字符串存在,则应替换这些单词和其余单词之间的空格

我想要最终答案为“圣诞节-Spl-每月”

提前感谢

php str-replace
5个回答
0
投票

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

$string = 'Christmas Spl - - Monthly';

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

echo $new;

圣诞节-Spl-每月


2
投票

解决方案:

仅用于破折号(-)

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

如果要多个破折号空格也转换为单破折号,也可以尝试此操作

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

0
投票

最简单的方法是使用str_replace两次。首先将-替换为,然后将替换为-

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

因此,内部str_replace给您Christmas Spl Monthly,外部Christmas-Spl-Monthly


0
投票

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

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

我先用多余的空格删除了连字符,然后用连字符替换了空格。所需的输出将是。

// Christmas-Spl-Monthly

0
投票

function dashedName()

我具有此功能,因为生成ID相当普遍。

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

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

旁注:此实现比公认的答案快很多(〜3倍)。

© www.soinside.com 2019 - 2024. All rights reserved.