모범 사례 : PHP에서 길고 여러 줄로 된 문자열로 작업합니까?
참고 : 이것이 매우 간단한 질문이라면 유감이지만 내 코드 형식에 대해 다소 강박 적입니다.
전자 메일의 본문을 구성하는 문자열을 반환하는 함수가있는 클래스가 있습니다. 이 텍스트가 전자 메일에 올바르게 표시되도록 형식을 지정하고 싶지만 코드가 펑키하게 보이지 않습니다. 여기 내가 의미하는 바가있다 :
class Something
{
public function getEmailText($vars)
{
$text = 'Hello ' . $vars->name . ",
The second line starts two lines below.
I also don't want any spaces before the new line, so it's butted up against the left side of the screen.";
return $text;
}
}
그러나 다음과 같이 쓸 수도 있습니다.
public function getEmailText($vars)
{
$text = "Hello {$vars->name},\n\rThe second line starts two lines below.\n\rI also don't want any spaces before the new line, so it's butted up against the left side of the screen.";
return $text;
}
그러나 새로운 줄과 캐리지 리턴은 어떻게 처리됩니까? 차이점이 뭐야? 인가 \n\n
에 해당하는 \r\r
나 \n\r
? 선 사이에 선 간격을 만들 때 어떤 것을 사용해야합니까?
그런 다음 출력 버퍼링 및 heredoc 구문 옵션이 있습니다.
객체에 긴 여러 줄 문자열을 사용하는 방법은 무엇입니까?
HEREDOC 또는 NOWDOC을 사용해야합니다.
$var = "some text";
$text = <<<EOT
Place your text between the EOT. It's
the delimiter that ends the text
of your multiline string.
$var
EOT;
Heredoc과 Nowdoc의 차이점은 heredoc에 포함 된 PHP 코드가 실행되는 반면 Nowdoc의 PHP 코드는 그대로 인쇄된다는 것입니다.
$var = "foo";
$text = <<<'EOT'
My $var
EOT;
이 경우 $ text의 값은 My $var
입니다.
참고 : 닫기 전에 EOT;
공백이나 탭이 없어야합니다. 그렇지 않으면 오류가 발생합니다
나는 pix0r과 비슷한 시스템을 사용하며 코드를 읽을 수 있다고 생각합니다. 때로는 실제로 줄 바꿈을 큰 따옴표로 분리하고 문자열의 나머지 부분에 작은 따옴표를 사용하는 경우가 있습니다. 이렇게하면 텍스트의 나머지 부분에서 눈에 띄며 큰 따옴표로 묶은 문자열에 연결하는 대신 연결을 사용하면 변수가 더 잘 나타납니다. 따라서 원래 예제를 사용하여 이와 같은 작업을 수행 할 수 있습니다.
$text = 'Hello ' . $vars->name . ','
. "\r\n\r\n"
. 'The second line starts two lines below.'
. "\r\n\r\n"
. 'I also don\'t want any spaces before the new line,'
. ' so it\'s butted up against the left side of the screen.';
return $text;
줄 바꿈과 관련하여 이메일에는 항상 \ r \ n을 사용해야합니다. PHP_EOL은 php가 실행되는 것과 동일한 운영 체제에서 사용되는 파일을위한 것입니다.
긴 텍스트에 템플릿을 사용합니다.
email-template.txt는 다음을 포함합니다
hello {name}!
how are you?
PHP에서 나는 이것을한다 :
$email = file_get_contents('email-template.txt');
$email = str_replace('{name},', 'Simon', $email);
문자열 중간에 추가 \n
및 / 또는 \r
중간에 코드가 너무 길면 두 번째 예와 같이 기분이 좋지 않습니다. 코드를 읽을 때 결과가 표시되지 않으며 스크롤해야합니다 .
이런 종류의 상황에서 나는 항상 Heredoc (또는 Nowdoc, PHP> = 5.3을 사용하는 경우)을 사용합니다 : 작성하기 쉽고, 읽기 쉽고, 긴 줄이 필요하지 않습니다 ...
예를 들면 :
$var = 'World';
$str = <<<MARKER
this is a very
long string that
doesn't require
horizontal scrolling,
and interpolates variables :
Hello, $var!
MARKER;
단 한 가지 : 끝 마커 (및 그 ;
뒤에 ' ')가 줄에있는 유일한 것이어야합니다 : 전후에 공백 / 탭이 없습니다!
Sure, you could use HEREDOC, but as far as code readability goes it's not really any better than the first example, wrapping the string across multiple lines.
If you really want your multi-line string to look good and flow well with your code, I'd recommend concatenating strings together as such:
$text = "Hello, {$vars->name},\r\n\r\n"
. "The second line starts two lines below.\r\n"
. ".. Third line... etc";
This might be slightly slower than HEREDOC or a multi-line string, but it will flow well with your code's indentation and make it easier to read.
I like this method a little more for Javascript but it seems worth including here because it has not been mentioned yet.
$var = "pizza";
$text = implode(" ", [
"I love me some",
"really large",
$var,
"pies.",
]);
// "I love me some really large pizza pies."
For smaller things, I find it is often easier to work with array structures compared to concatenated strings.
Related: implode vs concat performance
The one who believes that
"abc\n" . "def\n"
is multiline string is wrong. That's two strings with concatenation operator, not a multiline string. Such concatenated strings cannot be used as keys of pre-defined arrays, for example. Unfortunately php does not offer real multiline strings in form of
"abc\n"
"def\n"
only HEREDOC
and NOWDOC
syntax, which is more suitable for templates, because nested code indent is broken by such syntax.
In regards to your question about newlines and carriage returns:
I would recommend using the predefined global constant PHP_EOL as it will solve any cross-platform compatibility issues.
This question has been raised on SO beforehand and you can find out more information by reading "When do I use the PHP constant PHP_EOL"
but what's the deal with new lines and carriage returns? What's the difference? Is \n\n the equivalent of \r\r or \n\r? Which should I use when I'm creating a line gap between lines?
No one here seemed to actualy answer this question, so here I am.
\r
represents 'carriage-return'
\n
represents 'line-feed'
The actual reason for them goes back to typewriters. As you typed the 'carriage' would slowly slide, character by character, to the right of the typewriter. When you got to the end of the line you would return the carriage and then go to a new line. To go to the new line, you would flip a lever which fed the lines to the type writer. Thus these actions, combined, were called carriage return line feed. So quite literally:
A line feed,\n
, means moving to the next line.
A carriage return, \r
, means moving the cursor to the beginning of the line.
Ultimately Hello\n\nWorld
should result in the following output on the screen:
Hello
World
Where as Hello\r\rWorld
should result in the following output.
It's only when combining the 2 characters \r\n
that you have the common understanding of knew line. I.E. Hello\r\nWorld
should result in:
Hello
World
And of course \n\r
would result in the same visual output as \r\n
.
Originally computers took \r
and \n
quite literally. However these days the support for carriage return is sparse. Usually on every system you can get away with using \n
on its own. It never depends on the OS, but it does depend on what you're viewing the output in.
Still I'd always advise using \r\n
wherever you can!
you can also use:
<?php
ob_start();
echo "some text";
echo "\n";
// you can also use:
?>
some text can be also written here, or maybe HTML:
<div>whatever<\div>
<?php
echo "you can basically write whatever you want";
// and then:
$long_text = ob_get_clean();
'IT story' 카테고리의 다른 글
CSS로 문자열로 시작하는 ID를 선택하는 방법 (Javascript가 아닌)? (0) | 2020.05.25 |
---|---|
분산 형 데이터 세트를 사용하여 MatPlotLib에서 히트 맵 생성 (0) | 2020.05.25 |
Mac에서 ssh-copy-id를 어떻게 설치합니까? (0) | 2020.05.25 |
Spring으로 선택적 경로 변수를 만들 수 있습니까? (0) | 2020.05.25 |
Laravel 4 : Eloquent ORM을 사용하여 "주문"하는 방법 (0) | 2020.05.25 |