공백을 어떻게 분해하고 다듬을 수 있습니까?
예를 들어이 문자열의 요소에서 배열을 만들고 싶습니다.
$str = 'red, green, blue ,orange';
나는 당신이 그들을 폭발하고 반복하고 다룰 수 있다는 것을 알고 있습니다.
$arr = explode(',', $str);
foreach ($arr as $value) {
$new_arr[] = trim($value);
}
그러나 이것을 처리 할 수있는 한 줄 접근법이 있다고 생각합니다. 어떤 아이디어?
array_map을 사용하여 다음을 수행 할 수 있습니다 .
$new_arr = array_map('trim', explode(',', $str));
개선 된 답변
preg_split ('/(\s*,*\s*)*,+(\s*,*\s*)*/', 'red, green thing ,, ,, blue ,orange');
결과:
Array
(
[0] => red
[1] => green thing
[2] => blue
[3] => orange
)
이
- 쉼표로만 분할
- 각 항목에서 공백을 제거합니다.
- 빈 항목을 무시합니다
- "녹색 물건"과 같은 내부 공간으로 항목을 분할하지 않습니다
다음은 또한 입력 문자열의 시작 / 끝에서 공백을 처리합니다.
$new_arr = preg_split('/\s*,\s*/', trim($str));
그리고 이것은 모든 합리적인 위치에 공백이있는 최소 테스트입니다.
$str = ' first , second , third , fourth, fifth ';
$new_arr = preg_split('/\s*,\s*/', trim($str));
var_export($str);
기존 답변에 교장 중 일부를 결합하여
preg_split ('/\s*,+\s*/', 'red, green thing ,, ,, blue ,orange', NULL, PREG_SPLIT_NO_EMPTY);
그 이유는 이 답변 에서 버그를 발견 했기 때문에 문자열 끝에 쉼표가 있으면 배열의 빈 요소를 반환합니다. 즉
preg_split ('/(\s*,*\s*)*,+(\s*,*\s*)*/', 'red, green thing ,, ,, blue ,orange,');
결과
Array
(
[0] => red
[1] => green thing
[2] => blue
[3] => orange
[4] => ''
)
이 답변 에서 언급 한대로 PREG_SPLIT_NO_EMPTY 를 사용 하여이 문제 를 제거 하여 해결할 수 있지만 일단 수행하면 기술적으로 정규식을 통해 연속적인 쉼표를 제거 할 필요가 없으므로 표현이 단축됩니다.
한 줄 정규 표현식 으로이 작업을 수행 할 수도 있습니다
preg_split('@(?:\s*,\s*|^\s*|\s*$)@', $str, NULL, PREG_SPLIT_NO_EMPTY);
이 시도:
$str = preg_replace("/\s*,\s*/", ",", 'red, green, blue ,orange');
구체적 으로 OP의 샘플 문자열은 일치시킬 각 하위 문자열이 단일 단어이므로 str_word_count ()를 사용할 수 있습니다 .
코드 : ( 데모 )
$str = ' red, green, blue ,orange ';
var_export(str_word_count($str,1)); // 1 means return all words in an indexed array
산출:
array (
0 => 'red',
1 => 'green',
2 => 'blue',
3 => 'orange',
)
This can also be adapted for substrings beyond letters (and some hyphens and apostrophes -- if you read the fine print) by adding the necessary characters to the character mask / 3rd parameter.
Code: (Demo)
$str = " , Number1 , 234, 0 ,4heaven's-sake , ";
var_export(str_word_count($str,1,'0..9'));
Output:
array (
0 => 'Number1',
1 => '234',
2 => '0',
3 => '4heaven\'s-sake',
)
Again, I am treating this question very narrowly because of the sample string, but this will provide the same desired output:
Code: (Demo)
$str = ' red, green, blue ,orange ';
var_export(preg_match_all('/[^, ]+/',$str,$out)?$out[0]:'fail');
You can use preg_split() for that.
$bar = preg_split ('/[,\s]+/', $str);
print_r ($bar);
/* Result:
Array
(
[0] => red
[1] => green
[2] => blue
[3] => orange
)
*/
$str = str_replace(" ","", $str);
trim and explode
$str = 'red, green, blue ,orange';
$str = trim($str);
$strArray = explode(',',$str);
print_r($strArray);
참고URL : https://stackoverflow.com/questions/19347005/how-can-i-explode-and-trim-whitespace
'IT story' 카테고리의 다른 글
lodash를 사용하여 객체에서 정의되지 않은 null 값을 제거하는 방법은 무엇입니까? (0) | 2020.06.21 |
---|---|
jQuery : .ready () 중에 문서 제목을 변경하는 방법은 무엇입니까? (0) | 2020.06.21 |
내 Github 리포지토리에서 파일을 가져 오려고 시도하는 경우 : "관련되지 않은 기록을 병합하지 않음" (0) | 2020.06.21 |
AppCompat ActionBarActivity를 사용하여 상태 표시 줄 색상 변경 (0) | 2020.06.21 |
루비가 왜 메소드 오버로딩을 지원하지 않습니까? (0) | 2020.06.21 |