在包含标点符号的数组中创建单词串

时间:2013-09-20 14:20:52

标签: php

说我有一个输入,例如:

$input = "This is some sample input, it's not complex. ";
$input .="But does contain punctuation such as full stops / back-slashes / etc";
$array = arrayFunction($input);

我的问题是:我需要在arrayFunction中为$array提供以下内容:

$array = array(
    0 =>  "This",
    1 =>  "is",
    2 =>  "some",
    3 =>  "sample",
    4 =>  "input",
    5 =>  ",",
    6 =>  "it's",
    7 =>  "not",
    8 =>  "complex",
    9 =>  ".",
    10 =>  "But",
    11 =>  "does",
    12 =>  "contain",
    13 =>  "punctuation",
    14 =>  "such",
    15 =>  "as",
    16 =>  "full",
    17 =>  "stops",
    18 =>  "/",
    19 =>  "back-slashes",
    20 =>  "etc",
);

我一直在做以下

function arrayFunction($input)
{
    $explode = explode( " ", $input );
    $output  = array();
    foreach ( $explode as $word )
    {
        $output[] = trim( \String::lower( preg_replace('/[^\w|\s|-]+/', '', $word ) ) );
    }

    return $output;
}

哪个适用于我的需求,但现在我需要输出包含标点符号,以便我可以通过以下测试:

$input  = "This is some sample input, it's not complex.";
$input .= "But does contain punctuation such as full stops/back-slashes/etc";
$array  = arrayFunction($input);

$test  = implode(' ', $array);
if ($test == $input) {
  echo 'PASS';
} else {
  echo 'FAIL';
}

感谢。

编辑我想这样做的方法是通过空格爆炸然后循环结果并通过标点符号进一步分割。

编辑感谢下面接受的答案,我能够将代码重写为有效的代码。对于那些感兴趣的人,可以在这里看到https://gist.github.com/carbontwelve/6639350

2 个答案:

答案 0 :(得分:1)

这将产生您想要的数组:

function arrayFunction($input) {
    return preg_split('/(\s|[\.,\/])/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
}

但是因为你想通过测试,你需要知道空格的位置,所以我可以建议'/([\s\.,\/])/'作为你的正则表达式,但是你需要去掉空值来得到你想要的数组。另外,为了使用建议的正则表达式通过测试,您需要在没有空格的情况下进行$test = implode("", $array);

答案 1 :(得分:1)

对于测试使用低功能

if (\String::lower($test) == \String::lower($input)) {
  echo "PASS";
}

同样用于检查$ test和$ input字符串的输出并将其直接比较