Php 将字符串创建为包含标点符号的数组

Php 将字符串创建为包含标点符号的数组,php,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); 我的问题是:对于$array,我需要在arrayFunction中执行什么操作才能等于以下值: $array = array(

假设我有一个输入,例如:

$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);
我的问题是:对于
$array
,我需要在
arrayFunction
中执行什么操作才能等于以下值:

$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';
}
谢谢

编辑我想这样做的方式是按空格展开,然后循环该结果,再按标点进一步拆分


编辑多亏了下面被接受的答案,我才能够将我的代码改写成有效的代码。对于感兴趣的人,可以在这里看到它

这将生成您想要的阵列:

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

但是,因为您想要通过测试,您需要知道空格在哪里,所以我可以建议将
'/([\s\,\/])/'
作为正则表达式,但是您需要去掉空值以获得所需的数组。另外,要使用建议的正则表达式通过测试,您需要执行
$test=introde(“,$array”)不带空格。

对于测试,也使用lower函数

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

另外,对于复选框,将$test和$input字符串的输出设置为可见,并将其进行比较

,这样您就需要一个由
内爆
反转的函数了?您已经在当前代码中使用了
explode
?还有什么要说的吗?出于兴趣,strtolower()有什么问题吗?
\String::lower()
的作用是什么?没有任何现成的东西会同时分解,并且,您需要为此编写一个自定义函数。@Jon在数组中我想要的内容之间可能并不总是有空格。例如,
stops/back slashes/etc
input,
也应该在
arrayFunction
的输出中作为单独的元素拆分,您发布的数组将无法通过该测试。在
的两边都会有一个空格。谢谢,我不太懂正则表达式,但这对我很有帮助。看起来是我开始写的一个更好的解决方案:)@carbon12您可能需要添加
也是,因为它们都是常见的标点符号。将字符放在方括号之间将捕获它们。所以,正如@H2Ooooo建议的,您可能需要添加更多标点符号<代码>“/([\s\,\/:;!?])/”
将实现这一点。