企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# PHP 字符串 > 原文: [https://zetcode.com/lang/php/strings/](https://zetcode.com/lang/php/strings/) 在 PHP 编程教程的这一部分中,我们将更详细地处理字符串数据。 字符串是计算机语言中非常重要的数据类型。 这就是为什么我们将一整章专门讨论在 PHP 中使用字符串的原因。 ## PHP 字符串字面值 字符串字面值是表示计算机程序文本内的字符串值的符号。 在 PHP 中,可以使用单引号,双引号或使用 heredoc 或 nowdoc 语法创建字符串。 `literals.php` ```php <?php $a = "PHP"; $b = 'PERL'; echo $a, $b; ``` 在此代码示例中,我们创建两个字符串并将它们分配给`$a`和`$b`变量。 我们用`echo`关键字打印它们。 第一个字符串使用双引号定界符创建,第二个字符串使用单引号定界符。 下一个示例将使用 heredoc 语法创建一个字符串。 Heredoc 保留文本中的换行符和其他空格(包括缩进)。 heredoc 使用`<<<`来创建,后跟定界标识符,然后从下一行开始,在要引用的文本之后,再在同一行中以相同的标识符关闭。 结束标识符不能缩进。 它只能包含字母数字字符和下划线,并且必须以非数字字符或下划线开头。 `heredoc.php` ```php <?php $str = <<<TEXT "That is just as I intended." Vautrin said. "You know quite well what you are about. Good, my little eaglet! You are born to command, you are strong, you stand firm on your feet, you are game! I respect you." TEXT; echo $str, "\n"; ``` 该示例打印直接语音的示例。 ```php $ php heredoc.php "That is just as I intended." Vautrin said. "You know quite well what you are about. Good, my little eaglet! You are born to command, you are strong, you stand firm on your feet, you are game! I respect you." ``` 这是示例的输出。 nowdoc 的指定方式与 Heredoc 相似,但是在 nowdoc 内部未进行任何解析。 nowdoc 的标识与 Heredocs 所使用的序列相同`<<<`,但是后面的标识符用单引号引起来,例如`<<<'TEXT'`。 `nowdoc.php` ```php <?php $str = <<<'TEXT' Fear is among the greatest obstacles which prevent us from enjoying life to its fullest extent. Since of the most commonly held fears among people are the fear of heights and the fear of falling from heights. Rock climbing is a fantastic way to conquer these fears. TEXT; echo $str, "\n"; ``` 该示例使用 nowdoc 语法打印三个句子。 ```php $ php nowdoc.php Fear is among the greatest obstacles which prevent us from enjoying life to its fullest extent. Since of the most commonly held fears among people are the fear of heights and the fear of falling from heights. Rock climbing is a fantastic way to conquer these fears. ``` 这是`nowdoc.php`脚本的输出。 ## PHP 插值 变量被插入双引号中的字符串中。 `interpolation.php` ```php <?php $quantity = 5; echo "There are $quantity roses in the vase\n"; ``` `$quantity`变量将在字符串输出中替换为其值。 ```php $ php interpolation.php There are 5 roses in the vase ``` 这是`interpolation.php`脚本的输出。 当变量名称位于另一个字符旁边时,可以使用大括号。 `curlybraces.php` ```php <?php $quantity = 5; $item_name = "rose"; echo "There are $quantity {$item_name}s in the vase\n"; ``` 没有花括号,PHP 解释器将查找`$item_names`变量,该变量不存在。 ```php $ php curlybraces.php There are 5 roses in the vase ``` 这是`curlybraces.php`脚本的输出。 ## PHP 字符串连接 PHP 使用点`.`运算符来连接字符串。 ```php php > echo "PHP " . "language\n"; PHP language ``` 该示例连接了两个字符串。 ```php php > $a = "Java "; php > $a .= "language\n"; php > echo $a; Java language ``` PHP 还支持`.=`复合运算符。 ## PHP 转义字符 转义字符是指定用于对字符序列中紧随其后的字符调用替代解释的单个字符。 ```php php> echo " bbb\raaa"; aaabbb ``` 回车`\r`是控制字符,用于将行尾返回到行首。 `strophe.php` ```php <?php echo "Incompatible, it don't matter though\n'cos someone's bound to hear my cry\n"; echo "Speak out if you do\nYou're not easy to find\n"; ``` 新行是一个控制字符,它开始一行新文本。 ```php $ php strophe.php Incompatible, it don't matter though 'cos someone's bound to hear my cry Speak out if you do You're not easy to find ``` 这是`strophe.php`脚本的输出。 ```php php> echo "Towering\tinferno\n"; Towering inferno ``` 水平选项卡在文本之间放置一个空格。 ```php "Johnie's dog" 'Johnie\'s dog' ``` 单引号和双引号可以嵌套。 或者,如果仅使用单引号,则可以使用反斜杠来转义单引号的默认含义。 `backslash.php` ```php <?php $text = " \"That is just as I intended.\" Vautrin said. \"You know quite well what you are about. Good, my little eaglet! You are born to command, you are strong, you stand firm on your feet, you are game! I respect you.\" "; echo $text; ``` 在此示例中,我们有一个多行文本,其中包括直接语音。 双引号用反斜杠字符转义。 ```php php> $var = 233; php> echo "$var"; 233 php> echo "\$var is $var"; $var is 233 ``` 美元符号`$`在 PHP 中也有特殊含义; 它表示一个变量。 如果在字符串中使用了变量,则会对其进行插值,即使用变量的值。 为了回显变量名,我们转义了`$`字符`\$`。 ## PHP 字符串操作 PHP 具有大量有用的有用内置函数,可用于处理字符串。 ```php echo strlen("Eagle"); # prints 5 echo strtoupper("Eagle"); # prints EAGLE echo strtolower("Eagle"); # prints eagle ``` 在这里,我们使用三个函数。 `strlen()`函数返回字符串中的许多字符。 `strtoupper()`将字符转换为大写字母,`strtolower()`将字符转换为小写字母。 `letters.php` ```php <?php $sentence = "There are 22 apples"; $alphas = 0; $digits = 0; $spaces = 0; $length = strlen($sentence); for ($i = 0; $i < $length; $i++) { $c = $sentence[$i]; if (ctype_alpha($c)) $alphas++; if (ctype_digit($c)) $digits++; if (ctype_space($c)) $spaces++; } echo "There are $length characters.\n"; echo "There are $alphas alphabetic characters.\n"; echo "There are $digits digits.\n"; echo "There are $spaces spaces.\n"; ``` 在我们的示例中,我们有一个字符串句子。 我们计算句子中的绝对字符数,字母字符数,数字和空格。 为此,我们使用以下函数:`strlen()`,`ctype_alpha()`,`ctype_digit()`和`ctype_space()`。 ```php $ php letters.php There are 19 characters. There are 14 alphabetic characters. There are 2 digits. There are 3 spaces. ``` 这是`letters.php`脚本的输出。 接下来,我们介绍`substr()`函数。 ```php echo substr("PHP language", 0, 3); # prints PHP echo substr("PHP language", -8); # prints language ``` 该函数返回字符串的一部分。 第一个参数是指定的字符串。 第二个参数是子字符串的开头。 第三个参数是可选的。 它是返回的子字符串的长度。 默认值为返回到字符串末尾。 `str_repeat()`函数将字符串重复指定的次数。 `repeat.php` ```php <?php echo str_repeat("#", 18); echo "\nProject Neurea\n"; echo "Priority high\n"; echo "Security maximum\n"; echo str_repeat("#", 18); echo "\n"; ``` 我们使用`str_repeat()`函数创建两行`#`字符。 ```php $ php repeat.php ################## Project Neurea Priority high Security maximum ################## ``` 这是`repeat.php`脚本的输出。 在下一个示例中,我们将随机修改一个字符串。 `shuffling.php` ```php <?php $string = "ZetCode"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; echo str_shuffle($string), "\n"; ``` `str_shuffle()`随机随机播放一个字符串。 ```php $ php shuffling.php ZtCeoed eodtCZe toZeeCd oCdeteZ edtCZoe tdeCeoZ oeZdteC ``` 这是`shuffling.php`脚本的示例输出。 `explode()`函数用于将字符串分成多个部分。 它返回一个分割字符串部分的数组。 `exploding.php` ```php <?php $nums = "1,2,3,4,5,6,7,8,9,10,11"; $vals = explode(",", $nums); $len = count($vals); echo "There are $len numbers in the string\n"; ``` 字符串中包含整数,并用逗号分隔。 我们计算整数的数量。 ```php $vals = explode(",", $nums); ``` 在这里,我们使用`explode()`函数分割文本。 每当找到点`,`字符时,该函数就会将其切成小段。 ```php $ php exploding.php There are 11 numbers in the string ``` 示例的输出。 `teams1.php` ```php <?php echo "Ajax Amsterdam" . " - " . "Inter Milano " . "2:3\n"; echo "Real Madridi" . " - " . "AC Milano " . "3:3\n"; echo "Dortmund" . " - " . "Sparta Praha ". "2:1\n"; ``` 我们用点运算符连接字符串。 ```php $ php teams1.php Ajax Amsterdam - Inter Milano 2:3 Real Madridi - AC Milano 3:3 Dortmund - Sparta Praha 2:1 ``` 输出不是最佳的。 我们将对其进行更改,以使其看起来更整洁。 `teams2.php` ```php <?php $teams = array( array("Ajax Amsterdam", "Inter Milano"), array("Real Madrid", "AC Milano"), array("Dortmund", "Sparta Praha") ); $results = array("2:3", "3:3", "2:1"); $i = 0; foreach ($teams as $team) { echo str_pad($team[0], 14); echo str_pad("-", 3, " ", STR_PAD_BOTH); echo str_pad($team[1], 14); echo str_pad($results[$i], 3, " ", STR_PAD_LEFT); echo "\n"; $i++; } ``` 我们使用`str_pad()`函数改善了输出格式。 它将在字符串的左侧,右侧或两侧添加指定的字符串(在我们的示例中为空格)。 ```php $ php teams2.php Ajax Amsterdam - Inter Milano 2:3 Real Madrid - AC Milano 3:3 Dortmund - Sparta Praha 2:1 ``` 我们设法提供了更好的格式化输出。 ## 字符数组 PHP 中的字符串是一个字符数组。 `array_of_chars.php` ```php <?php $site = "zetcode.com"; for ($i=0; $i < strlen($site); $i++) { $o = ord($site[$i]); echo "$site[$i] has ASCII code $o\n"; } ``` 在示例中,我们遍历字符串并打印每个字符的 ASCII 码。 ```php $site = "zetcode.com"; ``` 定义了一个字符串。 它包含十一个字符。 ```php for ($i=0; $i < strlen($site); $i++) { $o = ord($site[$i]); echo "$site[$i] has ASCII code $o\n"; } ``` 我们使用`for`循环遍历字符串。 字符串的大小由`strlen()`函数确定。 `ord()`函数返回字符的 ASCII 值。 我们使用数组索引符号来获取字符。 ```php $ php array_of_chars.php z has ASCII code 122 e has ASCII code 101 t has ASCII code 116 c has ASCII code 99 o has ASCII code 111 d has ASCII code 100 e has ASCII code 101 . has ASCII code 46 c has ASCII code 99 o has ASCII code 111 m has ASCII code 109 ``` 这是`array_of_chars.php`示例的输出。 ## PHP 字符串格式化 字符串格式化或字符串插值是将各种值动态地放入字符串中。 `fruits.php` ```php <?php printf("There are %d oranges and %d apples in the basket.\n", 12, 32); ``` 我们使用`%d`格式说明符。 指定者希望传递一个整数值。 ```php $ php fruits.php There are 12 oranges and 32 apples in the basket. ``` 在下一个示例中,我们传递一个`float`和一个字符串值。 `height.php` ```php <?php printf("Height: %f %s\n", 172.3, "cm"); ``` 浮点值的格式说明符为`%f`,字符串为`%s`。 ```php $ php height.php Height: 172.300000 cm ``` 我们可能不喜欢上面示例中的数字默认情况下具有 6 个小数位的事实。 我们可以控制格式说明符中的小数位数。 `height2.php` ```php <?php printf("Height: %.1f %s\n", 172.3, 'cm'); ``` 小数点后跟一个整数控制小数位数。 在我们的例子中,数字恰好有一位小数。 ```php $ php height2.php Height: 172.3 cm ``` 下面的示例显示其他格式设置选项。 `formatting.php` ```php <?php # hexadecimal printf("%x\n", 300); # octal printf("%o\n", 300); # scientific printf("%e\n", 300000); ``` 第一种格式适用于十六进制数字。 `x`字符以十六进制格式格式化数字。 `o`字符以八进制格式显示数字。 `e`字符以科学格式显示数字。 ```php $ php formatting.php 12c 454 3.000000e+5 ``` 下一个示例显示三列数字。 `columns.php` ```php <?php foreach (range(1,11) as $num) { echo $num , " ", $num*$num, " ", $num*$num*$num, "\n"; } ``` 数字左对齐,输出不整齐。 ```php $ php columns.php 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331 ``` 为了解决这个问题,我们使用宽度说明符。 宽度说明符定义对象的最小宽度。 如果对象小于宽度,则将填充空格。 `columns2.php` ```php <?php foreach (range(1,11) as $num) { printf("%2d %3d %4d\n", $num, $num*$num, $num*$num*$num); } ``` 现在输出看起来正常。 数字 2 表示第一列的宽度为 2 个字符。 ```php $ php columns2.php 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 11 121 1331 ``` PHP 教程的这一部分介绍了字符串。