【问题标题】:PHP strip string of everything but letters and spaces, then convert spaces to dashesPHP去除除字母和空格之外的所有字符串,然后将空格转换为破折号
【发布时间】:2017-12-28 00:51:12
【问题描述】:

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

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

所以例如我想转:

例子:

Let's Start! => lets-start

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

【问题讨论】:

  • 你想让大写变成小写吗?当你想要破折号时,为什么你的代码有下划线?
  • 先用空字符串替换[^\w\d\s],然后用破折号替换[\s]
  • @IlyaBursov 我不太了解正则表达式或如何做到这一点。
  • 然后先阅读任何关于正则表达式的手册

标签: php regex string


【解决方案1】:

不用regx

也能得到同样的结果

示例:

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

echo $title; //Output: lets-start

【讨论】:

    【解决方案2】:
    $string = mb_strtolower( strtr("Let's start!", array('.' => '', ',' => '', '!' => '', '\''  => '') ) );
    echo  $string = preg_replace("/[\s]/", "-", $string);
    

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

    【讨论】:

    • 撇号有问题,我认为这可能是 wordpress 问题。它正在拉动 the_title 变量。
    • @JamesMitchell 变体将改为使用"'" => ''。 (双引号包围单引号)
    【解决方案3】:

    你可以使用这个表达式:

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

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

    $title = html_entity_decode($title);
    

    【讨论】:

    • 那变成了让我们开始吧!进入 let8217s-start
    • 听起来你不是在处理 ASCII 撇号,@JamesMitchell。
    • 尝试使用u (Unicode) 修饰符(答案已更新)。还要确保您的输入字符串不是 HTML 编码的。它应该是一个字面引用,而不是像 HTML 编码中的 #&8217;
    • 嗯,是的,这可能是撇号的 wordpress 问题,因为该部分仍然不起作用。
    • 这就是我试图解决的问题!没有意识到我必须解码它。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2012-02-05
    • 2016-12-21
    • 1970-01-01
    • 2013-01-16
    • 2016-04-02
    • 2011-08-29
    • 2011-02-16
    • 1970-01-01
    相关资源
    最近更新 更多