Option 1 (spaces)
选项1(空格)
keyword keyword keyword
Option 2 (line breaks)
选项2(换行符)
keyword
keyword
keyword
Option 3 (commas)
选项3(逗号)
keyword, keyword, keyword
Or would I have to use the split function instead? And if so, how?
或者我是否必须使用拆分功能?如果是这样,怎么样?
3 个解决方案
#1
4
Try using preg_split
but notice that this will explode on all of your examples at once.
尝试使用preg_split但请注意,这会立即在所有示例上爆炸。
$parts = preg_split("/[ ,\n]/", $string);
Edit: For the third example you give you'll get empty array elements as it's being split on both the comma and the space. Pass $parts
through array_filter()
to strip these out.
编辑:对于第三个示例,您将获得空数组元素,因为它在逗号和空格上分开。通过array_filter()传递$ parts以去除它们。
#3
0
str_word_count() for the win!
This task does not require variable delimiters or regex - assuming all of these "keywords" are "words"...
此任务不需要变量分隔符或正则表达式 - 假设所有这些“关键字”都是“单词”...
Code: (Demo)
$strings=[
'keyword keyword keyword',
'keyword
keyword
keyword',
'keyword, keyword, keyword'
];
foreach($strings as $string){
var_export(str_word_count($string,1));
echo "\n";
}
Output:
array (
0 => 'keyword',
1 => 'keyword',
2 => 'keyword',
)
array (
0 => 'keyword',
1 => 'keyword',
2 => 'keyword',
)
array (
0 => 'keyword',
1 => 'keyword',
2 => 'keyword',
)
#1
4
Try using preg_split
but notice that this will explode on all of your examples at once.
尝试使用preg_split但请注意,这会立即在所有示例上爆炸。
$parts = preg_split("/[ ,\n]/", $string);
Edit: For the third example you give you'll get empty array elements as it's being split on both the comma and the space. Pass $parts
through array_filter()
to strip these out.
编辑:对于第三个示例,您将获得空数组元素,因为它在逗号和空格上分开。通过array_filter()传递$ parts以去除它们。
#2
#3
0
str_word_count() for the win!
This task does not require variable delimiters or regex - assuming all of these "keywords" are "words"...
此任务不需要变量分隔符或正则表达式 - 假设所有这些“关键字”都是“单词”...
Code: (Demo)
$strings=[
'keyword keyword keyword',
'keyword
keyword
keyword',
'keyword, keyword, keyword'
];
foreach($strings as $string){
var_export(str_word_count($string,1));
echo "\n";
}
Output:
array (
0 => 'keyword',
1 => 'keyword',
2 => 'keyword',
)
array (
0 => 'keyword',
1 => 'keyword',
2 => 'keyword',
)
array (
0 => 'keyword',
1 => 'keyword',
2 => 'keyword',
)