๊ฐœ๋ฐœ๊ด€๋ จ/PHP

[PHP] ๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ๋ฐฐ์—ด์„ ๋ฌธ์ž์—ด๋กœ explode/implode ํ•จ์ˆ˜ ์‚ฌ์šฉ๋ฒ•๊ณผ ์˜ˆ์ œ

๐Ÿป๊ณฐ์ด๐Ÿป 2022. 8. 3.
728x90

์•ˆ๋…•ํ•˜์„ธ์š” ๊ณฐ์ด์—์š”:)

๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ๋ฐฐ์—ด์„ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜๋ฅผ ์†Œ๊ฐœ์‹œ์ผœ๋“œ๋ฆด๊ฑด๋ฐ์š” ใ…Žใ…Ž

 

๋ฐฐ์—ด์„ ๋ฌธ์ž์—ด๋กœ ๋งŒ๋“ค์–ด์ฃผ๋Š” ํ•จ์ˆ˜๋Š” explode ๋ผ๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค.

 

๋ฐ˜๋ฉด ๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค์–ด์ฃผ๋Š” ํ•จ์ˆ˜๋Š” implode ์ž…๋‹ˆ๋‹ค.

 

์„ค๋ช…

 

explode ๋ž€?

 

explode = ๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ๋ถ„ํ• 

 

string๋ฌธ์ž์—ด๋กœ ๊ตฌ์„ฑ๋œ ๊ฒฝ๊ณ„์—์„œ ๋ถ„ํ• ํ•˜์—ฌ ํ˜•์„ฑ๋œ ํ•˜์œ„ ๋ฌธ์ž์—ด์ธ ๋ฌธ์ž์—ด ๋ฐฐ์—ด์„ ๋ฐ˜ํ™˜ ํ•ฉ๋‹ˆ๋‹ค.

 

explode(๊ตฌ๋ถ„์ž, ๋ฌธ์ž์—ด)

 

implode ๋ž€?

 

implode  = ๋ฐฐ์—ด ์š”์†Œ๋ฅผ ๋ฌธ์ž์—ด๋กœ ๊ฒฐํ•ฉ

 

๊ฐ ์š”์†Œ ์‚ฌ์ด์— ๊ตฌ๋ถ„ ๊ธฐํ˜ธ ๋ฌธ์ž์—ด์ด ์žˆ๋Š” ๋™์ผํ•œ ์ˆœ์„œ๋กœ ๋ชจ๋“  ๋ฐฐ์—ด ์š”์†Œ์˜ ๋ฌธ์ž์—ด ํ‘œํ˜„์„ ํฌํ•จํ•˜๋Š” ๋ฌธ์ž์—ด์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

 

implode(๋‚˜๋ˆŒ ๊ตฌ๋ถ„์ž, ๋ฐฐ์—ด)

 

 

๊ฐ„๋‹จํ•œ ์‚ฌ์šฉ ์˜ˆ์ œ

์šฐ์„  explode ๋ถ€ํ„ฐ ํ•ด๋ณผ๊นŒ์š”?

<?php
	//explode ์‚ฌ์šฉ๋ฒ•

	$string = "one two three";
	
	$rtn = explode(" ", $string);

	echo print_r($rtn);
?>

์šฐ์„ ์ ์œผ๋กœ ์ €๋Š” ์ŠคํŽ˜์ด์Šค๋ฐ” ๊ธฐ์ค€๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„์ž๋ฅผ ์ง€์—ˆ์Šต๋‹ˆ๋‹ค.

 

์œ„ ์†Œ์Šค์— ์ถœ๋ ฅ๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

Array ( [0] => one [1] => two [2] => three ) 1

๋ฐฐ์—ด์ธ ์ƒํƒœ๋ผ์„œ echo๋กœ ์ถœ๋ ฅ ์‹œ Array ๋ผ๊ณ  ๋‚˜์˜ค๊ธฐ๋•Œ๋ฌธ์— print_r() ์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

 

key[0] = one

key[1] = two

key[2] = three

๋กœ ๋“ค์–ด๊ฐ€์žˆ๋„ค์š” ใ…Žใ…Ž

<?php
	//explode ์‚ฌ์šฉ๋ฒ•

	$string = "one two three";
	
	$rtn = explode(" ", $string);

	echo $rtn[1];
?>

$rtn์— ํ‚ค๊ฐ’์ด 1๋ฒˆ์ธ๊ฑธ ์ถœ๋ ฅํ•˜๊ฒŒ๋œ๋‹ค๋ฉด

two

์ด๋ ‡๊ฒŒ ๋‚˜์˜ค๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

 

๊ทธ๋ ‡๋‹ค๋ฉด implode๋Š” ์–ด๋–ค์‹์œผ๋กœ ์“ธ๊นŒ์š”??

<?php
	//implode ์‚ฌ์šฉ๋ฒ•

	$array = array("one", "two", "three");

	echo implode(",", $array);
?>

์ถœ๋ ฅ๊ฒฐ๊ณผ

one,two,three

 

๋งˆ์น˜ $array[0] . $array[1] . $array[2] ์ถœ๋ ฅํ•œ๊ฒƒ์ฒ˜๋Ÿผ ๋ฐฐ์—ด์•ˆ์— ํ‚ค๊ฐ’์„ ์„ค์ •ํ•ด๋‘” ๊ตฌ๋ถ„์ž๋ฅผ ๋„ฃ์–ด์„œ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด๋กœ ๋งŒ๋“ค์–ด์ฃผ๋„ค์š”

 

array_merge๋ฅผ ์ด์šฉํ•˜์—ฌ ๋ฐฐ์—ด์„ ๋Š˜๋ ค์„œ๋„ ๊ฐ€๋Šฅํ•œ์ง€ ํ•ด๋ดค์Šต๋‹ˆ๋‹ค.

<?php
	//implode ์‚ฌ์šฉ๋ฒ•

	$array = array("one", "two", "three");
	$array2 = array("four", "five", "six");

	$result = array_merge($array, $array2);

	echo implode(" ", $result);
?>

์ถœ๋ ฅ๊ฒฐ๊ณผ

 

one two three four five six

์ด๋ฒˆ์—” ์ฝค๋งˆ๋กœ ๊ตฌ๋ถ„์•ˆํ•˜๊ณ  ๊ณต๋ฐฑ์œผ๋กœ ํ–ˆ์Šต๋‹ˆ๋‹ค.

 

๊ฐœ๋ฐœํ•˜์‹ค๋•Œ ์•„์ฃผ ์œ ์šฉํ•˜๊ณ  ์ž์ฃผ์“ฐ์ด๋Š” ํ•จ์ˆ˜ ์†Œ๊ฐœํ•ด๋“œ๋ ธ์Šต๋‹ˆ๋‹ค.

 

๊ถ๊ธˆํ•˜์‹ ์  ์žˆ์œผ์‹œ๋ฉด ๋Œ“๊ธ€๋‚จ๊ฒจ์ฃผ์„ธ์š”!!

 

ํ˜ธํ™˜ ๊ฐ€๋Šฅํ•œ ๋ฒ„์ „

PHP 4, PHP 5, PHP 7, PHP 8 ๋ฒ„์ „์—์„œ ์‚ฌ์šฉํ•˜์‹ค์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€