PHP删除除字母和空格之外的所有内容的字符串,然后将空格转换为破折号

时间:2017-07-21 21:00:29

标签: php regex string

这是我尝试过的,但它没有删除撇号,有没有更好的方法呢?

$title = strtr($title, array('.' => '', ',' => '', '!' => '', '\''  => ''));
$title = preg_replace('/\s+/', '-', $title);

例如,我想转向:

示例:

Let's Start! => lets-start

但我正在努力寻找适用于所有情况的解决方案。

3 个答案:

答案 0 :(得分:4)

你可以使用这个表达式:

strtolower(preg_replace("#\s+#u", "-", preg_replace("#[^\w\s]|_#u", "", $title)))

注意:如果您的原始字符串包含HTML编码,例如’,那么您必须首先使用以下代码对其进行解码:

$title = html_entity_decode($title);

答案 1 :(得分:0)

const authenticate = (username, password) => {
    return axios
        .post('http://localhost:8000/api/auth/login/', {username, password})
        .then((response) => {
            console.log('RESPONSE: ', response.data);
            return response.data;
        })
        .catch((error) => {
            throw error;
        });
};

这应该替换字符,然后将所有空格更改为破折号。

答案 2 :(得分:0)

如果没有 regx

,您可以获得相同的结果

实施例

$title = "Let's Start!";
$title = strtr(strtolower($title), array('.' => '', ',' => '', '!' => '', '\''  => ''));
$title = str_replace(' ','-',trim($title));

echo $title; //Output: lets-start
相关问题