개발 꿀팁/PHP

PHP 배열과 문자열 변환 (초상세)

Jammie 2022. 8. 9. 12:19
반응형

1, 배열 회전 문자열
implode
방법 소개:

function implode ($glue = "", array $pieces) {}

주로 두 개의 파라미터가 있다
하나는 커넥터(g)입니다.lue:풀), 기본은 빈 문자열
하나는 배열입니다

사용하다.

$test = array("hello","world","php");
echo implode("-",$test);

결과:
hello-world-php
K-V 형식의 배열이라면?

$test = array("h"=>"hello","w"=>"world","p"=>"php");
echo implode("-",$test);

결국 hello-world-php
역시 밸류에만 효과가 있다는 설명이다.

2, 문자열이 배열로 분할됨
2.1 글자별로 나누기

function explode ($delimiter, $string, $limit = null) {}

explode(폭발, 이 문자열을 폭파시켰나?)
매개 변수 설명:
delimiter, 구분 기호
리미트
문서 구글 번역 결과:
limit이 양수이면 반환되는 배열에 최대 제한 요소가 포함됩니다소, 마지막 요소는 나머지 문자열들을 포함합니다.
개인적인 이해:
limit 분할된 부분만 제한합니다. 마지막 부분은 나머지 문자열입니다.잘라서 남은 것은 물론 1이면 문자열입니다.그 자체 (이미 실험)
코드 데모:

$str="hello-world-php";
$result = explode("-", $str);
var_dump($result);
$result = explode("-", $str,2);
var_dump($result);

출력 결과:

array(3) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(5) "world"
  [2]=>
  string(3) "php"
}
array(2) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(9) "world-php"
}

2.2 거리별 읽기
문자열은 분할하지 않아도 될 수 있습니다.하지만 글자 하나하나를 꺼내서, 즉 하나씩 읽어내야 합니다.
원본 문서:

**
 * Convert a string to an array
 * @link http://php.net/manual/en/function.str-split.php
 * @param string $string <p>
 * The input string.
 * </p>
 * @param int $split_length [optional] <p>
 * Maximum length of the chunk.
 * </p>
 * @return array If the optional split_length parameter is
 * specified, the returned array will be broken down into chunks with each
 * being split_length in length, otherwise each chunk
 * will be one character in length.
 * </p>
 * <p>
 * false is returned if split_length is less than 1.
 * If the split_length length exceeds the length of
 * string, the entire string is returned as the first
 * (and only) array element.
 * @since 5.0
 */
function str_split ($string, $split_length = 1) {}

부분 번역:
배열 옵션 split_length 인자를 지정하면 반환된 배열은 길이가 split_length인 블록으로 분할됩니다. 그렇지 않으면 각 블록은 문자 길이입니다.
Convert a string to an array, 문자열을 배열로 돌리는 거잖아요. 용법은 별로 없어요.
5개 길이의 문자열이면 두 자릿수로 읽어보고, 두 자릿수 미만이면 마지막 자릿수는 남겨둘까요?
물론 추측으로는 데이터의 무결성을 위해 보존해야 할 것이다.

$str = "hello";
var_dump(str_split($str,2));

결과도 나의 추측과 같다

array(3) {
  [0]=>
  string(2) "he"
  [1]=>
  string(2) "ll"
  [2]=>
  string(1) "o"
}
반응형