【问题标题】:Removing unwanted whitespace in sub string in php?删除 php 子字符串中不需要的空格?
【发布时间】:2015-07-23 09:26:10
【问题描述】:

我有用户在搜索框中输入字符串的场景。如果输入的字符串超过一个单词,我会使用,

$text = "Hello World";
$pieces = explode(' ', $text);

我将获得第一个和第二个任期

$pieces['0'] & $pieces['1'].

但是,如果用户键入类似的内容,

$text = "Hello                    World";

我应该如何获得第二个任期?

如果我var_dump 结果,我得到了

array(12) {
  [0]=>
  string(5) "Hello"
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  [3]=>
  string(0) ""
  [4]=>
  string(0) ""
  [5]=>
  string(0) ""
  [6]=>
  string(0) ""
  [7]=>
  string(0) ""
  [8]=>
  string(0) ""
  [9]=>
  string(0) ""
  [10]=>
  string(0) ""
  [11]=>
  string(5) "World"
}

【问题讨论】:

标签: php string explode


【解决方案1】:

使用preg_split() 代替explode(),然后使用\s+\s 空格,+ 1 次或多次)作为分隔符。像这样:

$pieces = preg_split("/\s+/", $text);

【讨论】:

  • 我如何在 Jquery 中做同样的事情?可以使用 preg_split 吗?
  • @user3289108 参见:stackoverflow.com/a/650037/3933332,只需将这些您想要的字符放入字符类 ([])
【解决方案2】:

Rizier123 的回答足够有效,但如果您想避免使用使用正则表达式检查的preg_split,您可以使用空字符串获取数组,然后像这样删除其中的所有空元素:

$text = "Hello      World";
$pieces = array_filter(explode(' ', $text));

【讨论】:

    【解决方案3】:

    使用 this 将多个空格替换为单个空格

    $output = preg_replace('!\s+!', ' ', $text);
    

    然后拆分文本

    $pieces = explode(' ', $output);
    

    【讨论】:

      【解决方案4】:

      试试:

      <?php
      $text = "Hello World";
      
      // BONUS: remove whitespace from beginning and end of string
      
      $text = trim($text);
      
      // replace all whitespace with single space
      
      $text = preg_replace('!\s+!', ' ', $text);
      $pieces = explode(' ', $text);
      ?>
      

      【讨论】:

        猜你喜欢
        • 2011-09-02
        • 2012-03-25
        • 2016-06-29
        • 1970-01-01
        • 2011-12-24
        • 1970-01-01
        • 2014-07-14
        相关资源
        最近更新 更多