【问题标题】:How do you split a string into word pairs?如何将字符串拆分为单词对?
【发布时间】:2011-04-22 13:17:04
【问题描述】:

我正在尝试将字符串拆分为 PHP 中的单词对数组。例如,如果您有输入字符串:

"split this string into word pairs please"

输出数组应该是这样的

Array (
    [0] => split this
    [1] => this string
    [2] => string into
    [3] => into word
    [4] => word pairs
    [5] => pairs please
    [6] => please
)

一些失败的尝试包括:

$array = preg_split('/\w+\s+\w+/', $string);

这给了我一个空数组,并且

preg_match('/\w+\s+\w+/', $string, $array);

将字符串拆分成单词对但不重复单词。是否有捷径可寻?谢谢。

【问题讨论】:

  • 正则表达式并不总是“字符串”的答案

标签: php regex arrays string


【解决方案1】:

为什么不直接使用 explode ?

$str = "split this string into word pairs please";

$arr = explode(' ',$str);
$result = array();
for($i=0;$i<count($arr)-1;$i++) {
        $result[] =  $arr[$i].' '.$arr[$i+1];
}
$result[] =  $arr[$i];

Working link

【讨论】:

  • split this, string 怎么样?
  • @stereofrog,也许是preg_split() 拆分为\W 或类似的
  • 我在您的解决方案中的 for 循环之后添加了 if ((count($arr) % 2) != 0) { $result[] = $arr[count($arr) - 1]; } 以获取最后一个单词,效果很好,谢谢。
【解决方案2】:

你可以explode这个字符串然后循环遍历它:

$str = "split this string into word pairs please";
$strSplit = explode(' ', $str);
$final = array();    

for($i=0, $j=0; $i<count($strSplit); $i++, $j++)
{
    $final[$j] = $strSplit[$i] . ' ' . $strSplit[$i+1];
}

我认为这可行,但应该有更简单的解决方案。

经过编辑使其符合 OP 的规范。 - 根据 codaddict

【讨论】:

  • 您的输出不符合 OP 的要求。
  • 哇,你的正确 coddict,讽刺的是,我实际上认为你的答案是错误的。
  • $j 的使用完全是多余的。
【解决方案3】:

如果您想使用正则表达式重复,则需要某种前瞻或后瞻。否则,表达式将不会多次匹配同一个单词:

$s = "split this string into word pairs please";
preg_match_all('/(\w+) (?=(\w+))/', $s, $matches, PREG_SET_ORDER);
$a = array_map(
  function($a)
  {
    return $a[1].' '.$a[2];
  },
  $matches
);
var_dump($a);

输出:

array(6) {
  [0]=>
  string(10) "split this"
  [1]=>
  string(11) "this string"
  [2]=>
  string(11) "string into"
  [3]=>
  string(9) "into word"
  [4]=>
  string(10) "word pairs"
  [5]=>
  string(12) "pairs please"
}

请注意,它不会按照您的要求重复最后一个词“请”,尽管我不确定您为什么想要这种行为。

【讨论】:

    【解决方案4】:
    $s = "split this string into word pairs please";
    
    $b1 = $b2 = explode(' ', $s);
    array_shift($b2);
    $r = array_map(function($a, $b) { return "$a $b"; }, $b1, $b2);
    
    print_r($r);
    

    给予:

    Array
    (
        [0] => split this
        [1] => this string
        [2] => string into
        [3] => into word
        [4] => word pairs
        [5] => pairs please
        [6] => please
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 2023-01-22
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多