开发者

Is it possible to have 3 delimiters for the explode function

Option 1 (spaces)

keyword keyword keyword

Option 2 (line breaks)

keyword
keyword
keyword

O开发者_开发知识库ption 3 (commas)

keyword, keyword, keyword

Or would I have to use the split function instead? And if so, how?


Try using preg_split but notice that this will explode on all of your examples at once.

$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.


Not as simple as preg_split, but strtok() is also an option


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',
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜