轨道
/
PHP
PHP
/
练习
/
高中恋人
高中恋人

高中恋人

学习练习

简介

字符串

字符串是一系列字符,用引号括起来。 单引号和双引号都支持。

<?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

说明

在这道练习中,你要帮助高中情侣在社交媒体上表白:用他们姓名缩写生成一个 ASCII 爱心:

     ******       ******
   **      **   **      **
 **         ** **         **
**            *            **
**                         **
**     J. K.  +  M. B.     **
 **                       **
   **                   **
     **               **
       **           **
         **       **
           **   **
             ***
              *

1. 获取名字的首字母

实现HighSchoolSweetheart::firstLetter函数。 它接收一个名字,返回这个名字的首字母。 它应该清理掉名字中多余的空白字符。

<?php

$sweetheart = new HighSchoolSweetheart();
$sweetheart->firstLetter("Jane");
# => "J"

2. 把首字母格式化为缩写

实现HighSchoolSweetheart::initial函数。 它接收一个名字,返回它的大写首字母,后面加一个点。 记得复用你在上一步定义的HighSchoolSweetheart::first_letter。

<?php

$sweetheart = new HighSchoolSweetheart();
$sweetheart->initial("jane");
# => "J."

3. 把全名拆分成名字和姓氏

实现HighSchoolSweetheart::initials函数。 它接收一个全名,全名由名字和姓氏组成,中间用空格分隔,然后返回姓名缩写。 记得复用你在上一步定义的HighSchoolSweetheart::initial。

<?php

$sweetheart = new HighSchoolSweetheart();
$sweetheart->initials("Jane Doe");
# => "J. D."

4. 把姓名缩写放进爱心里

实现HighSchoolSweetheart::pair函数。 它接收两个全名,返回放在 ASCII 爱心里的姓名缩写。 记得复用你在上一步定义的HighSchoolSweetheart::initials。

<?php

$sweetheart = new HighSchoolSweetheart();
$sweetheart->pair("Blake Miller", "Riley Lewis")
# => """
#      ******       ******
#    **      **   **      **
#  **         ** **         **
# **            *            **
# **                         **
# **     B. M.  +  R. L.     **
#  **                       **
#    **                   **
#      **               **
#        **           **
#          **       **
#            **   **
#              ***
#               *
# """
通过 GitHub 编辑 链接将在新窗口或新标签页中打开
PHP Exercism

准备好开始 高中恋人 了吗?

注册 Exercism,借助 11 个概念122 个练习 和真人导师指导,学习并掌握 PHP,全部免费。