문자열 배열 - explode() , split(), implode() ,array_splice
php 에서 문자열을 특정 문자열로 분리하는 함수는 explode() 과 split() 이 있다.
-. 두 함수 모두 결과가 배열로 반환된다.
-. explode() 는 전체 문자열(string)에서 특정 문자열(separator)을 기준으로 잘라내는 반면, split()는 단순 문자열 뿐만 아니라 패턴(pattern)을 사용하여 문자열을 나눌 수 있으며, 반환되는 배열 원소의 수를 제한(limit)할 수도 있다.
-. 형식.
array explode(string seprarator, string string) ;
array split(string pattern, string string, int [limit]) ;
-----------------------------------------------------------------------------------------
[ explode() 함수. ]
[ ex. ]
<?
$date = "2010/09/13" ;
// "/" 를 기준으로 $date 값을 $year, $month, $day 로 나누어 배열로 반환한다.
// explode() 함수는 구분자로 한가지만 사용할 수 있다.
// list() 함수는 list 안의 변수 $year, $month, $day 를
// 배열인 것처럼 다루는데 사용되는 함수다.
list($year, $month, $day) = explode("/",$date) ;
// 변수명 $year, $month, $day 와 한글을 붙여쓸 경우 실행 결과값을 볼수 없다.
// "$year년 $month월 $day일" 는 잘못된 코딩이다.
// php 는 한글도 변수명으로 사용할 수 있기 때문에 변수명뒤에 한글을 붙여쓰면 안된다.
echo "$year 년 $month 월 $day 일" ;
?>
[ 출력. ]
2010 년 09 월 13 일
-----------------------------------------------------------------------------------------
[ split() 함수. ]
[ ex. ]
<?
$datetime = "2010/09/13 23:45:46" ;
// split("[/ :]", $datetime) 함수에서 [/ :] 를 구분자로 나누어 배열 list 에 값을 대입한다.
list($year, $month, $day, $hour, $minute, $second) = split("[/ :]", $datetime) ;
echo "$year 년 $month 월 $day 일 $hour 시 $minute 분 $second 초" ;
?>
[ 출력. ]
2010 년 09 월 13 일 23 시 45 분 46 초
* 출처
http://area51.lesha.co.kr/index.php/?m=bbs&bid=program&uid=565
PHP에서는 implode() 함수로, 배열 요소들을 합쳐서 하나의 문자열로 만들 수 있습니다. Perl의 join 함수와 같은 역할을 합니다.
사용법은
implode ("구분기호", $배열명)
이렇고, 합친 결과를 문자열로서 반환합니다.
배열을 문자열로 합치기 예제 소스
소스 파일명: example.php
<head>
<title>PHP Example</title>
</head>
<body>
<?php
// 배열 정의
$a = array("Apple", "Google", "Nikon", 123, "Canon");
// 쉼표로 구분하여 배열을 문자열로 합치기
print implode(", ", $a) . "<br />\n";
// 출력: Apple, Google, Nikon, 123, Canon
// 슬래시(/) 기호를 구분자로 사용하여 합치기
print implode("/", $a) . "<br />\n";
// 출력: Apple/Google/Nikon/123/Canon
// 빈틈 없이 딱 붙이기
print implode("", $a) . "<br />\n";
// 출력: AppleGoogleNikon123Canon
// 공백으로 구분하여 합치기
print implode(" ", $a) . "<br />\n";
// 출력: Apple Google Nikon 123 Canon
// 합친 결과를 변수($s)에 저장하기
$s = implode("ㅎㅎ", $a);
print "$s<br />\n";
// 출력: AppleㅎㅎGoogleㅎㅎNikonㅎㅎ123ㅎㅎCanon
echo "<br /><br /><br />\n\n\n"; // 편의상 줄바꿈
// 합친 결과를 여러줄로 출력
$s = implode("<br />\n", $a);
print "$s";
/* 출력 결과:
Apple<br />
Google<br />
Nikon<br />
123<br />
Canon
*/
?>
</body>
</html>
-----------------------------------------------------------------------------------------------------------------------------------
array array_splice ( array input, int offset [, int length [, array replacement]] )
: 배열의 일부를 삭제하고, 그 위치에 다른 내용을 대체합니다
배열의 일부를 삭제만 하면 그 뒤 배열이 땡겨지고,
($a[10] 배열에서 $a[3] ~ $a[5] 구간을 삭제한다고 치면 $a[6]~$a[10]이 $a[3] 쪽으로 땡겨지는 것을 의미)
replacement 인자가 있다면 삭제한 구간에 해당 배열을 삽입합니다.
동치
array_push($input, $x, $y) | array_splice($input, count($input), 0, array($x, $y)) |
array_pop($input) | array_splice($input, -1) |
array_shift($input) | array_splice($input, -1) |
array_unshift($input, $x, $y) | array_splice($input, 0, 0, array($x, $y)) |
$a[$x] = $y | array_splice($input, $x, 1, $y) |
정의 및 사용
array_splice () 함수는 배열에서 선택한 요소를 제거하고 새로운 요소로 대체합니다.The function also returns an array with the removed elements. 이 기능은 또한 제거 된 요소 배열을 반환합니다.
팁 :기능 요소가 (길이 = 0)을 제거하지 않으면, 대체 배열이 시작 파라미터의 위치로부터 삽입한다 (실시 예 2 참조).
참고 :교체 된 배열의 키는 유지되지 않습니다.
array_splice( array,start,length,array )
Parameter | Description |
---|---|
array | Required. Specifies an array |
start | Required. Numeric value. Specifies where the function will start removing elements. 0 = the first element. If this value is set to a negative number, the function will start that far from the last element. -2 means start at the second last element of the array. |
length | Optional. Numeric value. Specifies how many elements will be removed, and also length of the returned array. If this value is set to a negative number, the function will stop that far from the last element. If this value is not set, the function will remove all elements, starting from the position set by the start-parameter. |
array | Optional. Specifies an array with the elements that will be inserted to the original array. If it's only one element, it can be a string, and does not have to be an array. |
기술적 세부 사항
반환 값 : | 추출 된 요소로 구성된 배열을 돌려줍니다 |
---|---|
PHP 버전 : | 4+ |
더 예
예 1
페이지의 상단에 예,하지만 출력과 같은 예는 반환 된 배열입니다 :
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("a"=>"purple","b"=>"orange");
print_r(array_splice($a1,0,2,$a2));
?>