Programming/$_머니 (PHP)

[PHP 기초] - sprintf 을 이용하여 HTML 태그 만들어내기

귀찮은 개발자 2024. 2. 9. 22:44
더보기

2022 년도에 작성된 글 입니다.

모던 PHP 유저 그룹 2022. 01 발표에서 sprintf 를 통한 가독성 좋은 문자열 표현에 대한 발표가 있었다. 

(Github Repo 에 자료 업로드 하는걸 깜빡했다.)

 

https://github.com/ModernPUG/meetup

 

GitHub - ModernPUG/meetup: Modern PHP User Group 정기모임 발표 자료

Modern PHP User Group 정기모임 발표 자료. Contribute to ModernPUG/meetup development by creating an account on GitHub.

github.com

 

당시 발표 내용을 보고 HTML 태그에도 사용할 수 있겠다. 라는 생각이 들어 정리해보았다.

 

아래의 예시 처럼 많은 파라미터를 전달할 경우 코드가 길어지고,

$result2 와 같이 상황에 따라 second 와 sixth 에 대한 key:value 가 빠질 수 있는 예외의 상황이 발생했다.

$arr = [
    "first" => 'first',
    "second" => 'second',
    "third" => 'third',
    "fourth" => 'fourth',
    "fifth" => 'fifth',
    "sixth" => 'sixth',
    "seventh" => 'seventh',
    "eighth" => 'eighth'
];

$exampleTag = "<tag first='%s' second='%s' third='%s' fourth='%s' fifth='%s' sixth='%s' seventh='%s' eighth='%s'></tag>";
$result = sprintf(
    $exampleTag,
    $arr['first'], $arr['second'], $arr['third'], $arr['fourth'], $arr['fifth'], $arr['sixth'], $arr['seventh'], $arr['eighth']
);

// 결과: <tag first='first' second='second' third='third' fourth='fourth' fifth='fifth' sixth='sixth' seventh='seventh' eighth='eighth'></tag>

$exampleTag2 = "<tag first='%s' third='%s' fourth='%s' fifth='%s' seventh='%s' eighth='%s'></tag>";
$result2 = sprintf(
    $exampleTag2,
    $arr['first'], $arr['third'], $arr['fourth'], $arr['fifth'], $arr['seventh'], $arr['eighth']
);
// 결과: <tag first='first' third='third' fourth='fourth' fifth='fifth' seventh='seventh' eighth='eighth'></tag>

위의 상황을 개선하기 위해 아래의 방법을 사용해 봤다.

// 01. Before (출력 동일)
$result = sprintf(
    $exampleTag,
    $arr['first'], $arr['second'], $arr['third'], $arr['fourth'], $arr['fifth'], $arr['sixth'], $arr['seventh'], $arr['eighth']
);

// 01. After (출력 동일하지만 아래 코드에서는 활용을 하지 못함.)
$result = vsprintf($exampleTag, $arr);

// 02. Before
$exampleTag2 = "<tag first='%s' third='%s' fourth='%s' fifth='%s' seventh='%s' eighth='%s'></tag>";
$result2 = sprintf(
    $exampleTag2,
    $arr['first'], $arr['third'], $arr['fourth'], $arr['fifth'], $arr['seventh'], $arr['eighth']
);

// 02-1. After (arguments 수가 일치하지 않아 에러발생)
$exampleTag2 = "<tag first='%s' second='%s' third='%s' fourth='%s' fifth='%s' sixth='%s' seventh='%s' eighth='%s'></tag>";
unset($arr['second']);
unset($arr['sixth']);
$result2 = vsprintf($exampleTag, $arr);

// 02-2. After (오히려 +2번 작업을 해야함.)
$exampleTag2 = "<tag first='%s' third='%s' fourth='%s' fifth='%s' seventh='%s' eighth='%s'></tag>";
unset($arr['second']);
unset($arr['sixth']);
$result2 = vsprintf($exampleTag2, $arr);

 

하지만 배열의 상황에 따라 어느 key => value 가 빠질지 몰라 아래와 같이 개선을 해봤는데
오히려 코드의 품질이 더 난독화 $exampleTag1 , $exampleTag2, $exampleTag3 등 여러개를 만들어서 관리해야 하나? 라는 문제가 발생했다.

$arr3 = [
    "first" => '"first=__first"',
    "second" => '',
    "third" => '"first=__third"',
    "fourth" => '"fourth=__fourth"',
    "fifth" => '"fourth=__fifth"',
    "sixth" => '',
    "seventh" => '"seventh=__seventh"',
    "eighth" => '"eighth=__eighth"'
];

$exampleTag3 = "<tag first second third fourth fifth sixth eighth></tag>";
$result3 = str_replace(array_keys($arr3), array_values($arr3), $exampleTag3);
// 결과: <tag "first=__first"  "first=__third" "fourth=__fourth" "fourth=__fifth"  "eighth=__eighth"></tag>

가장 배스트는 아래와 같은 방법으로 출력되는 것이다.

$arr = [
    "first" => 'first',
    "second" => 'second',
    "third" => 'third',
    "fourth" => 'fourth',
    "fifth" => 'fifth',
    "sixth" => 'sixth',
    "seventh" => 'seventh',
    "eighth" => 'eighth'
];
...
...
...
// 결과: <tag first='first' second='second' third='third' fourth='fourth' fifth='fifth' sixth='sixth' seventh='seventh' eighth='eighth'></tag>

$arr = [
    "first" => 'first',
    "third" => 'third',
    "fourth" => 'fourth',
    "fifth" => 'fifth',
    "seventh" => 'seventh',
    "eighth" => 'eighth'
];
...
...
...
// 결과: <tag first='first' third='third' fourth='fourth' fifth='fifth' seventh='seventh' eighth='eighth'></tag>

이런 경우 가장 최적의 방법은 Foreach 로 태그를 찍어내는 방법 이었다.

  
function printTag($arr)
{
	$tag = "<tag "
	foreach ($array as $key => $value) {
    	$tag = .$tag." $key=$value";
    }
    $tag = .$tag." ><tag/>"
    
    return $tag;
}