【问题标题】:Strip non alphanumeric characters and limit string to two words去除非字母数字字符并将字符串限制为两个单词
【发布时间】:2011-02-22 00:01:18
【问题描述】:

我正在尝试从字符串中去除非字母数字字符并将字符串限制为两个单词。即:

foo bar baz    => foo-bar
boo   * test   => boo-test
te%st_foo      => test-foo

到目前为止,我得到了这个:

$term = preg_replace('/[^A-Za-z0-9 ]/', '', $term);
$words = explode(" ", $term);
$generated = strtolower(implode(" ",array_splice($words,0,2)));
$term = preg_replace('!\s+!', '-', $term);

但是在某个地方出错了,这些是我刚刚拼凑起来的 sn-ps,试图得到我想要的结果。

问题真的是字符串中是否有超过 1 个空格等。

帮助表示赞赏:)

谢谢

【问题讨论】:

标签: php


【解决方案1】:

首先通过删除多余的空间来规范化字符串,如下所示:

preg_replace('/[ ]+/', ' ', $term);

然后做剩下的,它会工作的。

【讨论】:

    【解决方案2】:

    为了将多个 [white]spaces 减少为单个空间使用:

    $string = preg_replace("/[ \t\n\r]+/", " ", $string);
    

    在您的 explode 之前立即执行此操作。

    【讨论】:

      【解决方案3】:
      $str = preg_replace('/[^a-z]+/is', '-', $str);
      $str = trim(str_replace('--', '-', $str), '-');
      // now we have array of words
      $str = explode('-', $str);
      $str = $str[0].'-'.$str[1];
      

      UPD:

      <?php
          $str = 'foo&*^%#*$&@^     bar          asjdhakhsgd';
          $str = preg_replace('/[^a-z]+/is', '-', $str);
          $str = trim(str_replace('--', '-', $str), '-');
          $str = explode('-', $str);
          $str = $str[0].'-'.$str[1];
      
          echo $str; // foo-bar
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-28
        • 2018-10-21
        相关资源
        最近更新 更多