文字列は、引用符で囲まれた一連の文字です。 シングルクォートとダブルクォートの両方が使えます。
<?php
$where = "Spain";
$what = 'rain';
ダブルクォートで囲んだ文字列では、スコープ内にある変数を参照すると、その値が文字列の中に挿入されます。
<?php
$answer = 42;
$expanded = "The answer to life, the universe, and everything is $answer";
これまで、PHPの文字列関数はASCII文字しかサポートしておらず、現代のUnicodeエンコーディングには対応していませんでした。 ASCII文字はそれぞれ1バイトであるのに対し、Unicode文字は1〜4バイトの長さになることがあります。 Unicode文字列を安全に操作する必要がある場合は、従来の関数のマルチバイト版を参照してください。
<?php
$byte_length = strlen('😃'); // => 4
$string_length = mb_strlen('😃'); // => 1
この演習では、高校生の恋人同士がSNSで愛を告白できるよう、二人のイニシャルをあしらったASCIIのハートを作ります。
****** ******
** ** ** **
** ** ** **
** * **
** **
** J. K. + M. B. **
** **
** **
** **
** **
** **
** **
***
*
HighSchoolSweetheart::firstLetter関数を実装します。
名前を受け取り、その頭文字を返します。
名前から不要な空白を取り除きます。
<?php
$sweetheart = new HighSchoolSweetheart();
$sweetheart->firstLetter("Jane");
# => "J"
HighSchoolSweetheart::initial関数を実装します。
名前を受け取り、その頭文字を大文字にし、ピリオドを付けて返します。
前のステップで定義したHighSchoolSweetheart::first_letterを再利用してください。
<?php
$sweetheart = new HighSchoolSweetheart();
$sweetheart->initial("jane");
# => "J."
HighSchoolSweetheart::initials関数を実装します。
スペースで区切られた名と姓からなるフルネームを受け取り、イニシャルを返します。
前のステップで定義したHighSchoolSweetheart::initialを再利用してください。
<?php
$sweetheart = new HighSchoolSweetheart();
$sweetheart->initials("Jane Doe");
# => "J. D."
HighSchoolSweetheart::pair関数を実装します。
2つのフルネームを受け取り、ASCIIのハートの中にイニシャルを入れて返します。
前のステップで定義したHighSchoolSweetheart::initialsを再利用してください。
<?php
$sweetheart = new HighSchoolSweetheart();
$sweetheart->pair("Blake Miller", "Riley Lewis")
# => """
# ****** ******
# ** ** ** **
# ** ** ** **
# ** * **
# ** **
# ** B. M. + R. L. **
# ** **
# ** **
# ** **
# ** **
# ** **
# ** **
# ***
# *
# """