PHP字符串
最后修改于 2025 年 2 月 16 日
在本 PHP 编程教程中,我们将更详细地处理字符串数据。
字符串是一系列字符,其中一个字符与一个字节相同。
PHP 仅支持 256 个字符集;它不提供原生的 Unicode 支持。
PHP 字符串字面量
字符串字面量 是在计算机程序文本中表示字符串值的符号。 在 PHP 中,字符串可以使用单引号、双引号或使用 heredoc 或 nowdoc 语法创建。
<?php $a = "PHP"; $b = 'PERL'; echo $a, $b;
在此代码示例中,我们创建了两个字符串并将它们分配给 $a
和 $b
变量。 我们使用 echo
关键字打印它们。 第一个字符串是用双引号分隔符创建的,第二个字符串是用单引号创建的。
PHP 字符串 heredoc
heredoc 保留文本中的换行符和其他空格(包括缩进)。 heredoc 的创建方式是使用 <<<
后跟一个分隔符标识符,然后在下一行开始,后跟要引用的文本,然后用同一标识符(在其自己的行上)关闭。
关闭标识符不得缩进。 它只能包含字母数字字符和下划线,并且必须以非数字字符或下划线开头。
<?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 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."
PHP 字符串 nowdoc
nowdoc 的指定方式与 heredoc 类似,但在 nowdoc 内部不进行解析。 nowdoc 用与 heredocs 相同的 <<<
序列标识,但其后的标识符用单引号括起来,例如 <<<'TEXT'。
<?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 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.
PHP 字符串插值
变量在双引号括起来的字符串中进行插值。
<?php $quantity = 5; echo "There are $quantity roses in the vase\n";
$quantity
变量在其值在字符串输出中被替换。
$ php interpolation.php There are 5 roses in the vase
当变量名与另一个字符相邻时,可以使用花括号。
<?php $quantity = 5; $item_name = "rose"; echo "There are $quantity {$item_name}s in the vase\n";
如果没有花括号,PHP 解释器将查找 $item_names
变量,该变量不存在。
$ php curly_braces.php There are 5 roses in the vase
PHP 字符串连接
PHP 使用点 .
运算符连接字符串。
php > echo "PHP " . "language\n"; PHP language
该示例连接了两个字符串。
php > $a = "Java "; php > $a .= "language\n"; php > echo $a; Java language
PHP 还支持 .=
复合运算符。
PHP 转义字符
一个转义字符是一个指定用于在字符序列中对紧随其后的字符进行替代解释的单个字符。
php> echo " bbb\raaa"; aaabbb
回车 \r
是控制字符,用于换行返回到行首。
<?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 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
php> echo "Towering\tinferno\n"; Towering inferno
水平制表符在文本之间添加空格。
"Johnie's dog" 'Johnie\'s dog'
单引号和双引号可以嵌套。或者,如果我们只使用单引号,我们可以使用反斜杠来转义单引号的默认含义。
<?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> $var = 233; php> echo "$var"; 233 php> echo "\$var is $var"; $var is 233
美元符号 $
在 PHP 中也有特殊含义;它表示一个变量。 如果一个变量在字符串中使用,它会被插值,即使用变量的值。 要回显变量名,我们转义 $
字符 \$
。
PHP 字符串函数
PHP 具有大量有用的内置函数,可用于处理字符串。
echo strlen("Eagle"); # prints 5 echo strtoupper("Eagle"); # prints EAGLE echo strtolower("Eagle"); # prints eagle
在这里我们使用三个函数。 strlen
函数返回字符串中的字符数。 strtoupper
将字符转换为大写字母,而 strtolower
将字符转换为小写字母。
<?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 letters.php There are 19 characters. There are 14 alphabetic characters. There are 2 digits. There are 3 spaces.
接下来,我们介绍 substr
函数。
echo substr("PHP language", 0, 3); # prints PHP echo substr("PHP language", -8); # prints language
该函数返回字符串的一部分。 第一个参数是指定的字符串。 第二个参数是子字符串的开始。 第三个参数是可选的。 它是返回的子字符串的长度。 默认值是返回到字符串的末尾。
str_repeat
函数将字符串重复指定的次数。
<?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 repeat.php ################## Project Neurea Priority high Security maximum ##################
在下一个示例中,我们随机修改一个字符串。
<?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 shuffling.php ZtCeoed eodtCZe toZeeCd oCdeteZ edtCZoe tdeCeoZ oeZdteC
这是 shuffling.php
脚本的示例输出。
explode
函数用于将字符串拆分为多个部分。 它返回一个拆分字符串部分的数组。 implode
函数使用字符串连接数组元素。
<?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"; $nums2 = implode(',', $vals); echo $nums2 . "\n";
我们在一个字符串中用逗号分隔符分隔整数。 我们计算整数的个数。
$vals = explode(",", $nums);
在这里我们使用 explode
函数拆分文本。 该函数将在找到句点 ,
字符时将字符串分割成多个部分。
$ php expl_impl.php There are 11 numbers in the string 1,2,3,4,5,6,7,8,9,10,11
<?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 teams1.php Ajax Amsterdam - Inter Milano 2:3 Real Madridi - AC Milano 3:3 Dortmund - Sparta Praha 2:1
输出不是最优的。 我们将对其进行更改,使其看起来更整洁。
<?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 teams2.php Ajax Amsterdam - Inter Milano 2:3 Real Madrid - AC Milano 3:3 Dortmund - Sparta Praha 2:1
我们设法给出了一个更漂亮的格式化输出。
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 码。
$site = "zetcode.com";
定义了一个字符串。 它包含十一个字符。
for ($i=0; $i < strlen($site); $i++) { $o = ord($site[$i]); echo "$site[$i] has ASCII code $o\n"; }
我们使用 for 循环遍历字符串。 字符串的大小由 strlen
函数确定。 ord
函数返回字符的 ASCII 值。 我们使用数组索引表示法获取一个字符。
$ 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
PHP 字符串格式化
字符串格式化或字符串插值是将各种值动态放入字符串中。
<?php printf("There are %d oranges and %d apples in the basket.\n", 12, 32);
我们使用 %d
格式说明符。 说明符希望传递一个整数值。
$ php fruits.php There are 12 oranges and 32 apples in the basket.
在下一个示例中,我们传递一个浮点值和一个字符串值。
<?php printf("Height: %f %s\n", 172.3, "cm");
浮点值的格式说明符是 %f
,字符串的格式说明符是 %s
。
$ php height.php Height: 172.300000 cm
我们可能不喜欢上一个示例中的数字默认情况下有 6 位小数。 我们可以控制格式说明符中小数位数。
<?php printf("Height: %.1f %s\n", 172.3, 'cm');
小数点后跟一个整数控制小数位数。 在我们的例子中,该数字恰好有一位小数。
$ php height2.php Height: 172.3 cm
以下示例显示了其他格式选项。
<?php # hexadecimal printf("%x\n", 300); # octal printf("%o\n", 300); # binary printf("%b\n", 300); # scientific printf("%e\n", 300000);
第一种格式使用十六进制数。 x
字符以十六进制表示法格式化数字。 o
字符以八进制格式显示数字。 e
字符以科学格式显示数字。
$ php formatting.php 12c 454 100101100 3.000000e+5
下一个示例打印了三列数字。
<?php foreach (range(1,11) as $num) { echo $num , " ", $num*$num, " ", $num*$num*$num, "\n"; }
这些数字左对齐,输出不整洁。
$ 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
要纠正此问题,我们使用宽度说明符。 宽度说明符定义对象的最小宽度。 如果对象小于宽度,则用空格填充它。
<?php foreach (range(1,11) as $num) { printf("%2d %3d %4d\n", $num, $num*$num, $num*$num*$num); }
现在输出看起来没问题。 数字 2 表示第一列将是 2 个字符宽。
$ 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 字符串。
作者
列出所有 PHP 教程。