PHP字符串

在PHP编程教程的这一部分,我们将更详细地处理字符串数据。

$ php -v
php -v
PHP 8.1.2 (cli) (built: Aug  8 2022 07:28:23) (NTS)
...

我们使用PHP版本8.1.2。

字符串是一系列字符,其中一个字符等同于一个字节。

PHP只支持256个字符集;它不提供本机Unicode支持。

PHP字符串文字

字符串文字是在计算机程序文本中表示字符串值的符号。在PHP中,可以使用单引号、双引号或使用heredoc或nowdoc语法创建字符串。

<?php

$a = "PHP";
$b = 'PERL';

echo $a, $b;

在这个代码示例中,我们创建了两个字符串并将它们分配给$a$b变量。我们使用echo关键字打印它们。第一个字符串使用双引号分隔符创建,第二个字符串使用单引号分隔符创建。

PHP字符串文档

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相同的<<<序列来标识,但后面的标识符用单引号括起来,例如<<<'文本'。

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

在我们的示例中,我们有一个字符串句子。我们计算句子中的绝对字符数、字母字符数、数字和空格数。为此,我们使用以下函数:strlenctype_alphactype_digitctype_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教程。

赞(0) 打赏

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏