问题
How can I explode a string by one or more spaces or tabs?
Example:
A B C D
I want to make this an array.
回答1:
$parts = preg_split('/\s+/', $str);
回答2:
To separate by tabs:
$comp = preg_split("/[\t]/", $var);
To separate by spaces/tabs/newlines:
$comp = preg_split('/\s+/', $var);
To seperate by spaces alone:
$comp = preg_split('/ +/', $var);
回答3:
This works:
$string = 'A B C D';
$arr = preg_split('/[\s]+/', $string);
回答4:
The author asked for explode, to you can use explode like this
$resultArray = explode("\t", $inputString);
Note: you must used double quote, not single.
回答5:
I think you want preg_split:
$input = "A B C D";
$words = preg_split('/\s+/', $input);
var_dump($words);
回答6:
instead of using explode, try preg_split: http://www.php.net/manual/en/function.preg-split.php
回答7:
In order to account for full width space such as
full width
you can extend Bens answer to this:
$searchValues = preg_split("@[\s+ ]@u", $searchString);
Sources:
- strip out multi-byte white space from a string PHP
- What are all the Japanese whitespace characters?
(I don't have enough reputation to post a comment, so I'm wrote this as an answer.)
回答8:
The answers provided by other folks (Ben James) are quite good and I have used them. As user889030 points out, the last array element may be empty. Actually, the first and last array elements can be empty. The code below addresses both issues.
# Split an input string into an array of substrings using any set
# whitespace characters
function explode_whitespace($str) {
# Split the input string into an array
$parts = preg_split('/\s+/', $str);
# Get the size of the array of substrings
$sizeParts = sizeof($parts);
# Check if the last element of the array is a zero-length string
if ($sizeParts > 0) {
$lastPart = $parts[$sizeParts-1];
if ($lastPart == '') {
array_pop($parts);
$sizeParts--;
}
# Check if the first element of the array is a zero-length string
if ($sizeParts > 0) {
$firstPart = $parts[0];
if ($firstPart == '')
array_shift($parts);
}
}
return $parts;
}
回答9:
Explode string by one or more spaces or tabs in php example as follow:
<?php
$str = "test1 test2 test3 test4";
$result = preg_split('/[\s]+/', $str);
var_dump($result);
?>
/** To seperate by spaces alone: **/
<?php
$string = "p q r s t";
$res = preg_split('/ +/', $string);
var_dump($res);
?>
回答10:
@OP it doesn't matter, you can just split on a space with explode. Until you want to use those values, iterate over the exploded values and discard blanks.
$str = "A B C D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){
if ( trim($b) ) {
print "using $b\n";
}
}
来源:https://stackoverflow.com/questions/1792950/explode-string-by-one-or-more-spaces-or-tabs