dreamphp기록과 추억이 머무는 곳
Tip&Tech

문자열 사이 랜덤 위치에 지정한 만큼 특정 문자열 삽입

abcdefghijklmnopqrstuvwxyz

위와 같은 문자열이 있을 때 랜덤 위치에 문자열을 삽입,
예를 들어 아래와 같은 문자열을 얻는 방법입니다.

abc[BiHon]defghijk[DreamPHP.com]lmn[Hello]opqrst[PHP]uvw[Good-bye!]xyz
abcdef[Good bye!]ghijklmn[Hello][DreamPHP.com]opqrstuvw[PHP]xyz[BiHon]
:
실행하면 매번 다른 곳에 문자열 삽입입니다.

<?php

/*
모든 오류 출력. 습관을 들이면 갈수록 편해집니다.
+ error_reporting()
- http://php.net/manual/en/function.error-reporting.php
*/
error_reporting(E_ALL);

/*
기본 문자열입니다.
+ Strings
- http://php.net/manual/en/language.types.string.php
*/
$string = 'abcdefghijklmnopqrstuvwxyz';

/*
치환 전 문자열을 출력합니다.
+ Predefined Constants
- http://php.net/manual/kr/reserved.constants.php [한글 구 버전]
- http://php.net/manual/en/reserved.constants.php [영문 신 버전]
*/
echo $string.'<br />'.PHP_EOL;

/*
이 문자열에 삽입할 문자열을 배열에 원하는 만큼 추가합니다.
+ Arrays
- http://php.net/manual/en/language.types.array.php
*/
$insert = array(); // 배열 초기화
$insert[] = '[Hello]';
$insert[] = '[BiHon]';
$insert[] = '[DreamPHP.com]';
$insert[] = '[PHP]';
$insert[] = '[Good-bye!]';

/*
배열의 크기를 구합니다. 그리고 랜덤하게 입력하기 위해 섞습니다.
+ count()
- http://php.net/manual/kr/function.count.php
- http://php.net/manual/en/function.count.php
+ shuffle()
- http://php.net/manual/kr/function.shuffle.php
- http://php.net/manual/en/function.shuffle.php
*/
$size = count($insert);
shuffle($insert);

/*
이제 원래의 문자열 사이에 입력하기 위해 위치를 구합니다.
0부터 문자열 길이 사이의 랜덤한 위치를 구하면 됩니다.
삽입할 문자열의 배열 크기만큼 반복합니다.
참고로 중복 예외 처리는 하지 않았습니다. 필요한 for() 안에 조건 추가.
+ mt_rand()
- http://php.net/manual/kr/function.mt-rand.php
- http://php.net/manual/en/function.mt-rand.php
*/
$len = strlen($string);
$position = array(); // 위치 배열
for($i=0;$i<$size;$i++) $position[] = mt_rand(0,$len);

/*
랜덤이나 작은 순서대로 하면 원치 않는 결과가 나올 수 있으니
위치가 큰 순으로 정렬해줘야 합니다.
+ rsort()
- http://php.net/manual/kr/function.rsort.php
- http://php.net/manual/en/function.rsort.php
*/
rsort($position);

/*
이제 배열의 크기만큼 반복하며, 문자열을 삽입(치환)하면 됩니다.
substr_replace() 함수가 유용합니다.
+ substr_replace()
- http://php.net/manual/en/function.substr-replace.php
+ foreach()
- http://php.net/manual/kr/control-structures.foreach.php
- http://php.net/manual/en/control-structures.foreach.php
*/
foreach($position as $k => $p)
{
$string = substr_replace($string,$insert[$k],$p,0);
}

/*
치환 후 문자열을 출력합니다.
*/
echo $string."\n";

?>

* 실행 결과 (매번 변동)
abcdefghijklmnopqrstuvwxyz
[DreamPHP.com]abcde[Good-bye!]fghijklmn[PHP]opqrstuv[BiHon]w[Hello]xyz
목록

함께 나눈 이야기

댓글

댓글 남기기

이미지와 영상은 본문에 표시됩니다. 삭제한 첨부와 본문 연결은 수정 저장할 때 함께 반영됩니다.

취소

작성자 삭제 후에도 삭제 안내가 남으며 운영자는 원문을 확인할 수 있습니다.