PHP에서 sprintf 함수를 사용하는 이유는 무엇입니까?
PHP 함수 sprintf ()에 대해 더 배우려고하지만 php.net이 여전히 혼란스러워서 도움이되지 않았습니다. 왜 그것을 사용하고 싶습니까?
아래의 예를 살펴보십시오.
이것을 사용하는 이유 :
$output = sprintf("Here is the result: %s for this date %s", $result, $date);
이것이 동일하고 IMO 작성이 더 쉬운 경우 :
$output = 'Here is the result: ' .$result. ' for this date ' .$date;
여기에 뭔가 빠졌습니까?
sprintf
는 원본 printf의 모든 서식 기능을 갖추고 있으므로 문자열에 변수 값을 삽입하는 것 이상의 작업을 수행 할 수 있습니다.
예를 들어 숫자 형식 (16 진수, 10 진수, 8 진수), 소수, 패딩 등을 지정하십시오. printf 용 Google을 사용하면 많은 예를 찾을 수 있습니다. printf 의 wikipedia 기사 를 시작해야합니다.
sprintf에 대한 많은 사용 사례가 있지만 내가 사용하는 한 가지 방법은 다음과 같은 문자열을 저장하는 것입니다. '안녕하세요, 내 이름은 % s'입니다. 데이터베이스에 또는 PHP 클래스의 상수입니다. 그 문자열을 사용하고 싶을 때 간단히 이렇게 할 수 있습니다.
$name = 'Josh';
// $stringFromDB = 'Hello, My Name is %s';
$greeting = sprintf($stringFromDB, $name);
// $greetting = 'Hello, My Name is Josh'
본질적으로 코드에서 약간의 분리가 가능합니다. 내 코드의 여러 위치에서 'Hello, My Name is % s'를 사용하면 한 곳에서 '% s is my name'(으)로 변경할 수 있으며 각 인스턴스로 이동하거나 이동하지 않고도 다른 곳에서 자동으로 업데이트됩니다. 연결.
형식화 된 문자열에 나타나는 순서대로 배열 될 필요가없는 sprintf
인수로 현지화 된 응용 프로그램에서 다른 용도로 사용 sprintf
됩니다.
예:
$color = 'blue';
$item = 'pen';
sprintf('I have a %s %s', $color, $item);
그러나 프랑스어와 같은 언어는 단어를 다르게 주문합니다.
$color = 'bleu';
$item = 'stylo';
sprintf('J\'ai un %2$s %1$s', $color, $item);
(예, 프랑스어가 짜증납니다 : 학교에서 독일어를 배웠습니다!)
실제로는 gettext 를 사용하여 지역화 된 문자열을 저장하지만 아이디어를 얻습니다.
번역하기가 더 쉽습니다.
echo _('Here is the result: ') . $result . _(' for this date ') . $date;
번역 (gettext) 문자열은 다음과 같습니다.
- 결과는 다음과 같습니다.
- 이 날짜에
다른 언어로 번역 할 때 불가능하거나 매우 이상한 문장이 될 수 있습니다.
지금 가지고 있다면
echo sprintf(_("Here is the result: %s for this date %s"), $result, $date);
번역 (gettext) 문자열은 다음과 같습니다.
- 결과는 다음과 같습니다.이 날짜의 % s % s
훨씬 더 의미가 있고 다른 언어로 번역하는 것이 훨씬 더 유연합니다.
내가 찾은 가장 좋은 이유는 언어 파일에 모든 언어 문자열을 배치하여 사람들이 필요에 따라 번역하고 순서를 지정할 수 있었기 때문에 문자열의 형식에 관계없이 표시하려는 것입니다. 사용자 이름
예를 들어 사이트 상단에 "[[User]] 님을 환영합니다"라고 표시됩니다. 프로그래머 는 UI 사용자가 어떻게 작성하는지 알지 못 하거나 신경 쓰지 않습니다 . 사용자 이름이 메시지의 어딘가에 표시 될 것입니다.
따라서 메시지가 실제로 무엇인지 걱정하지 않고 코드에 메시지를 포함시킬 수 있습니다.
랭 파일 (EN_US) :
...
$lang['welcome_message'] = 'Welcome back %s';
...
그런 다음 실제 PHP 코드에서이를 사용하여 모든 언어로 모든 유형의 메시지를 지원할 수 있습니다.
sprintf($lang['welcome_message'], $user->name())
왜 그것을 사용하고 싶습니까?
언어 문자열에 (외부) 소스를 사용할 때 매우 유용합니다. 주어진 다국어 문자열에 고정 된 수의 변수가 필요한 경우 올바른 순서 만 알고 있으면됩니다.
en.txt
not_found = "%s could not be found."
bad_argument = "Bad arguments for function %s."
bad_arg_no = "Bad argument %d for function %s."
hu.txt
not_found = "A keresett eljárás (%s) nem található."
bad_argument = "Érvénytelen paraméterek a(z) %s eljárás hívásakor."
bad_arg_no = "Érvénytelen %d. paraméter a(z) %s eljárás hívásakor."
삽입 된 변수는 여러 언어의 시작 또는 끝에있을 필요조차 없으며 순서 만 중요합니다.
물론 약간의 성능 향상에도 불구 하고이 대체를 수행하는 자체 함수를 작성할 수는 있지만 언어 문자열을 읽을 수있는 클래스가있는 경우Language
훨씬 빠릅니다 .
/**
* throws exception with message($name = "ExampleMethod"):
* - using en.txt: ExampleMethod could not be found.
* - using hu.txt: A keresett eljárás (ExampleMethod) nem található.
*/
throw new Exception(sprintf(Language::Get('not_found'), $name));
/**
* throws exception with message ($param_index = 3, $name = "ExampleMethod"):
* - using en.txt: Bad argument 3 for function ExampleMethod.
* - using hu.txt: Érvénytelen 3. paraméter a(z) ExampleMethod eljárás hívásakor.
*/
throw new Exception(sprintf(Language::Get('bad_arg_no'), $param_index, $name));
또한의 모든 기능과 함께 제공 printf
되므로 다음과 같이 다양한 유형의 변수를 형식화 할 수있는 단일 라이너입니다.
언급했듯이 입력 데이터의 형식을 지정할 수 있습니다. 예를 들어, 2dp, 4 자리 숫자 등을 강제하는 등 MySQL 쿼리 문자열을 작성하는 데 매우 유용합니다.
또 다른 장점은 거의 매개 변수를 입력하는 것과 같이 문자열 레이아웃을 공급되는 데이터와 문자열 레이아웃을 분리 할 수 있다는 것입니다. 예를 들어, MySQL 쿼리의 경우 :
// For security, you MUST sanitise ALL user input first, eg:
$username = mysql_real_escape_string($_POST['username']); // etc.
// Now creating the query:
$query = sprintf("INSERT INTO `Users` SET `user`='%s',`password`='%s',`realname`='%s';", $username, $passwd_hash, $realname);
이 방법은 물론 HTML로 출력을 인쇄 할 때와 같은 다른 용도로 사용됩니다.
편집 : 보안상의 이유로 위의 기술을 사용할 때 MySQL 삽입 공격을 방지 하기 위해이 방법을 사용하기 전에 모든 입력 변수를 위생 처리해야합니다mysql_real_escape_string()
. 비 염소 입력을 구문 분석하면 사이트와 서버가 해킹 됩니다. (물론 코드에 의해 완전히 구성되고 안전하다는 보장은 제외합니다.)
sprintf ()를 사용하면 문자열을 포맷하는 것이 훨씬 깨끗하고 안전합니다.
예를 들어 입력 변수를 처리 할 때 예상 형식을 미리 지정하여 예기치 않은 놀라움을 방지합니다 (예 : 문자열 [ %s
] 또는 숫자 [ %d
]). 이것은 잠재적으로 SQL 인젝션 위험에 도움이 될 수 있지만 문자열이 따옴표로 구성되어 있으면 막을 수 없습니다.
또한 부동 소수점을 처리하는 데 도움 %.2f
이되며 변환 기능을 사용하지 못하게하는 자릿수 (예 :)를 명시 적으로 지정할 수 있습니다 .
다른 주요 장점은 대부분의 주요 프로그래밍 언어가 자체 구현 sprintf()
되어 있다는 점입니다. 일단 익숙해지면 새로운 언어를 배우는 대신 (문자열을 연결하거나 부동 소수점을 변환하는 방법) 사용하기가 훨씬 더 쉽습니다.
요약하면, 더 깨끗하고 읽기 쉬운 코드를 만들기 위해 사용하는 것이 좋습니다.
예를 들어 아래 실제 예를 참조하십시오 .
$insert .= "('".$tr[0]."','".$tr[0]."','".$tr[0]."','".$tr[0]."'),";
또는 예를 들어 인쇄하는 간단한 예 '1','2','3','4'
:
print "foo: '" . $a . "','" . $b . "'; bar: '" . $c . "','" . $d . "'" . "\n";
그리고 형식 문자열로 인쇄 :
printf("foo: '%d','%d'; bar: '%d','%d'\n", $a, $b, $c, $d);
where printf()
는와 동일 sprintf()
하지만 (변수에) 반환하지 않고 형식화 된 문자열을 출력합니다.
더 읽기 쉬운 것은 무엇입니까?
내가 최근에 사용하지 않았다면 나는 똑같은 일이지만. 사용자 입력을 기반으로 문서를 생성 할 때 편리합니다.
"<p>Some big paragraph ".$a["name"]." again have tot ake care of space and stuff .". $a["age"]. "also would be hard to keep track of punctuations and stuff in a really ".$a["token"]. paragarapoh.";
WHich는 다음과 같이 쉽게 쓸 수 있습니다
sprintf("Some big paragraph %s. Again have to take care of space and stuff.%s also wouldnt be hard to keep track of punctuations and stuff in a really %s paragraph",$a,$b,$c);
이:
"<p>Some big paragraph ".$a["name"]." again have to take care of space and stuff .". $a["age"]. "also would be hard to keep track of punctuations and stuff in a really ".$a["token"]. paragraph.";
또한 쓸 수 있습니다 :
"<p>Some big paragraph {$a['name']} again have to take care of space and stuff .{$a['age']} also would be hard to keep track of punctuations and stuff in a really {$a['token']} paragraph.";
내 의견으로는 이것이 더 명확하지만 지역화 또는 형식화에 대한 사용을 볼 수 있습니다.
일반적인 경우 중 일부는 출력 형식을보다 정확하게 제어해야하는 경우입니다. 예를 들어 길이에 따라 특정 값에 특정 양의 공백이 앞쪽에 채워지거나 숫자가 특정 정확한 형식으로 출력되는지 확인하는 것이 까다로울 수 있습니다.
또한 "쓰기가 더 쉬워진다"는 예를 들어 보자. 에코는 쓰기가 쉽지만, 특히 변수가 많은 경우 sprintf를 읽기가 더 쉽다.
sprintf 또는 printf를 사용하는 또 다른 이유는 사용자가 특정 값의 출력 형식을 정의하도록하려는 것입니다. sprintf 호환 가능 출력 형식을 안전하게 정의 할 수 있습니다.
Oh, and your example is actually wrong for one part. sprintf
returns the string, but echo
does not - echo
immediately outputs it and returns nothing, while sprintf
just returns it.
If you've used C/C++, then you would be used to the sprintf function.
There is a good chance that the second line is less efficient. Echo is designed as an output command, whereas sprintf is designed to do string token substitution. I'm not a PHP person, but I suspect that there are more objects involved with the echo. If it acts like Java would, it creates a new string each time something is added to the list, so you'd end up with 4 strings created.
Sometimes I got something like this, which I consider a little more easier to read:
$fileName = sprintf('thumb_%s.%s',
$fileId,
$fileInfo['extension']);
I usually use sprintf to ensure that a id that come from the user input is an integer for example:
// is better use prepared statements, but this is practical sometimes
$query = sprintf("SELECT * from articles where id = %d;",$_GET['article_id']);
Also is used to do rudimentary templates (for html mails or other things), so you can reuse a the the template in many places:
$mail_body = "Hello %s, ...";
$oneMail = sprintf($mail_body, "Victor");
$anotherMail = sprintf($mail_body, "Juan");
It's very useful also to format numbers in different representations (octal, control the decimal place, etc).
define('TEXT_MESSAGE', 'The variable "%s" is in the middle!');
sprintf(TEXT_MESSAGE, "Var1");
sprintf(TEXT_MESSAGE, "Var2");
sprintf(TEXT_MESSAGE, "Var3");
sprintf is particularly useful when formatting strings that use numbers. For example,
$oranges = -2.34;
echo sprintf("There are %d oranges in the basket", $oranges);
Output: There are -2 oranges in the basket
Oranges is formatted as a whole number (-2), but will wrap around to positive numbers if one uses %u for unsigned values. To avoid this behaviour, I use the absolute function, abs(), to round the number towards zero as follows:
$oranges = -5.67;
echo sprintf("There are %d oranges in the basket", abs($oranges));
Output: There are 5 oranges in the basket
The end result is a statement with high readability, logical construction, clear formatting, and flexibility for addition of additional variables as required. As the number of variables increases in combination with functions that manipulate these variables, the benefits become more apparent. As a final example:
$oranges = -3.14;
$apples = 1.5;
echo sprintf("There are %d oranges and %d apples", abs($oranges), abs($apples));
Output: There are 3 oranges and 4 apples
The left side of the sprintf statement clearly expresses the string and the types of expected values, while the right side clearly expressed the variables used and how they are being manipulated.
Well, sprintf
has many capabilities as we know an example as below:
Few months ago I was in need of converting seconds to hour:minute:seconds format Like $t = 494050 //seconds
i wanted to print like 137 h 14 m 10 s
so i came up with the php function springf()
i just hold the seconds in $t
and echo sprintf("%02d h %s%02d m %s%02d s", floor($t/3600), $f, ($t/60)%60, $f, $t%60);
gives me 137 h 14 m 10 s
sprintf() function is very useful one if we know how to use it.
The argument is the same one for using templates. You'll want to separate your Textsleev from the actual variable values. Besides the additional powers of sprintf that we're mentioned about it's just a style thing.
A really good use case for using sprintf is outputting padded formats of numbers and also, when mixing different types in a string. It can be easier to read in many cases and makes it super simple to print different representations of the same variable, especially numerical ones.
Using sprintf() function over ordinary concatenation has the advantage that you can apply different types of formatting on the variables to be concatenated.
In your case, you have
$output = sprintf("Here is the result: %s for this date %s", $result, $date);
and
$output = 'Here is the result: ' .$result. ' for this date ' .$date;
Let us take $result = 'passed'; date = '23rd';
Using ordinary concatenation you can only get the output:
Here is the result: passed for this date 23rd
However if you use sprintf()
you can get a modified output such as:
$output = sprintf('Here is the result: %.4s for this date %.2s',$result,$date);
echo $output;
Output:
Here is the result: pass for this date 23
sprintf()
is quite similar to printf()
. If you know printf()
in details then sprintf()
and even vsprintf()
is not really difficult to understand.
one of the things that differs sprintf()
from printf()
is that you will need declare a variable to catch the output from the function as it does not directly print/echo anything. Let see the following code snippets:
printf("Hello %s", "world"); // "Hello world"
sprintf("Hello %s", "world"); // does not display anything
echo sprintf("Hello %s", "world"); // "Hello world"
$a = sprintf("Hello %s", "world"); // does not display anything
echo $a;// "Hello world"
Hope that helps.
One "outputs", the other "returns", that's one of the main differences.
printf()
Outputs
sprintf()
Returns
You have to be careful when using sprintf in loops:
$a = 'Anton';
$b = 'Bert';
$c = 'Corni';
$d = 'Dora';
$e = 'Emiel';
$f = 'Falk';
$loops = 10000000;
$time = microtime(true);
for ($i = 0; $i < $loops; $i++)
{
$test = $a . $b . $c . $d . $e . $f;
}
$concatTime = microtime(true) - $time;
$time = microtime(true);
for ($i = 0; $i < $loops; $i++)
{
$test = "$a $b $c $d $e $f";
}
$concat2Time = microtime(true) - $time;
$time = microtime(true);
for ($i = 0; $i < $loops; $i++)
{
$test = sprintf('%s %s %s %s %s %s', $a, $b, $c, $d, $e, $f);
}
$sprintfTime = microtime(true) - $time;
echo 'Loops: ' . $loops . '<br>';
echo '\'$a . $b . $c . $d . $e . $f\'' . ' needs ' . $concatTime . 's<br>';
echo '"$a $b $c $d $e $f"' . ' needs ' . $concat2Time . 's<br>';
echo 'sprintf(\'%s %s %s %s %s %s\', $a, $b, $c, $d, $e, $f)' . ' needs ' . $sprintfTime . 's<br>';
Which leads to the following times (on my local machine with PHP 7.2):
Loops: 10000000
'$a . $b . $c . $d . $e . $f' needs 1.4507689476013s
"$a $b $c $d $e $f" needs 1.9958319664001s
sprintf('%s %s %s %s %s %s', $a, $b, $c, $d, $e, $f) needs 9.1771278381348s
I use it for messages to users or other "pretty" types of functionality. For instance if I know I'm going to use the user's name.
$name = 'Some dynamic name';
And have multiple messages to use in that situation. (I.e., blocking or following another user)
$messageBlock = 'You have blocked %s from accessing you.';
$messageFollow = 'Following %s is a great idea!';
You can create a general function that does something to the user and add this string, and no matter what the structure of the sentence it should look pretty nice. I always dislike just appending strings together and constantly using dot notation and closing and reopening strings just to make a sentence look good. I was a fan at first like most but this seems pretty useful when multiple strings need to be manipulated and you do not want to hard code the placement of the variable in every time.
Think of it, what looks better?
return $messageOne === true ? $name.'. Please use the next example' : 'Hi '.$name.', how are you?'
Or
$message = $messageOne === true ? 'Option one %s'
: ($messageTwo === true ? 'Option Two %s maybe?' : '%s you can choose from tons of grammatical instances and not have to edit variable placement and strings');
return sprintf($message, $name);
Sure its an extra step but what if your conditional checks do a bunch of other functional things, then the quotations and appending starts to get in the way of coding functionally.
참고URL : https://stackoverflow.com/questions/1386593/why-use-sprintf-function-in-php
'IT' 카테고리의 다른 글
구조 패딩 및 포장 (0) | 2020.05.17 |
---|---|
CTRL-r과 유사하게 검색 배쉬 히스토리를 전달할 수 없음 (0) | 2020.05.17 |
동일한 키 아래에 여러 값이있는 HashMap (0) | 2020.05.17 |
npm을 사용하여 현재 디렉토리에 package.json 종속성을 설치하는 방법 (0) | 2020.05.17 |
C 또는 C ++에서 작은 따옴표와 큰 따옴표 (0) | 2020.05.17 |