하나 이상의 공백 또는 탭으로 문자열 분해
하나 이상의 공백 또는 탭으로 문자열을 분해하려면 어떻게해야합니까?
예:
A B C D
이것을 배열로 만들고 싶습니다.
$parts = preg_split('/\s+/', $str);
탭으로 분리하려면 :
$comp = preg_split("/[\t]/", $var);
공백 / 탭 / 줄 바꾸기로 구분하려면 다음을 수행하십시오.
$comp = preg_split('/\s+/', $var);
공백만으로 분리하려면 :
$comp = preg_split('/ +/', $var);
이것은 작동합니다 :
$string = 'A B C D';
$arr = preg_split('/[\s]+/', $string);
저자는 폭발을 요청했습니다. 다음과 같이 폭발을 사용할 수 있습니다.
$resultArray = explode("\t", $inputString);
참고 : 작은 따옴표가 아닌 큰 따옴표를 사용해야합니다.
나는 당신이 원하는 것 같아요 preg_split
:
$input = "A B C D";
$words = preg_split('/\s+/', $input);
var_dump($words);
explode를 사용하는 대신 preg_split을 시도 하십시오 : http://www.php.net/manual/en/function.preg-split.php
다음 과 같은 전체 너비 공간 을 고려하기 위해
full width
Bens 답변을 다음과 같이 확장 할 수 있습니다.
$searchValues = preg_split("@[\s+ ]@u", $searchString);
출처 :
(댓글을 게시 할만큼 평판이 충분하지 않으므로 이것을 답변으로 작성했습니다.)
다른 사람들 (Ben James)이 제공 한 답변은 꽤 좋으며 사용했습니다. user889030이 지적했듯이 마지막 배열 요소는 비어있을 수 있습니다. 실제로 첫 번째 및 마지막 배열 요소는 비어있을 수 있습니다. 아래 코드는 두 가지 문제를 모두 해결합니다.
# 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;
}
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);
?>
@OP 그것은 중요하지 않습니다, 당신은 폭발로 공간에서 나눌 수 있습니다. 해당 값을 사용하기 전에는 분해 된 값을 반복하고 공백을 버립니다.
$str = "A B C D";
$s = explode(" ",$str);
foreach ($s as $a=>$b){
if ( trim($b) ) {
print "using $b\n";
}
}
참고 URL : https://stackoverflow.com/questions/1792950/explode-string-by-one-or-more-spaces-or-tabs
'Programing' 카테고리의 다른 글
ES6 모듈의 수입을 조롱하는 방법? (0) | 2020.06.30 |
---|---|
URL에서 JSON 객체 가져 오기 (0) | 2020.06.29 |
EF Core를 사용하여 ASP.NET Core에서 마이그레이션을 적용 취소하는 방법 (0) | 2020.06.29 |
lodash를 사용하여 Array에서 객체를 찾아 반환하는 방법은 무엇입니까? (0) | 2020.06.29 |
날짜 범위에서 일을 생성 (0) | 2020.06.29 |