PHP 字符串

本章我们将更详细地处理字符串数据,字符串是计算机语言中非常重要的数据类型。 这就是为什么我们将一整章专门讨论在 PHP 中使用字符串的原因。

PHP 字符串字面值

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

literals.php

<?php

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

echo a,b;

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

下一个示例将使用 heredoc 语法创建一个字符串。 Heredoc 保留文本中的换行符和其他空格(包括缩进)。 在[doc]中创建[doc],然后使用&lt;&lt;&lt;,后跟定界标识符,然后从下一行开始,在要引用的文本之后,再在同一行中以相同的标识符关闭。 结束标识符不能缩进。 它只能包含字母数字字符和下划线,并且必须以非数字字符或下划线开头。

heredoc.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;

echostr, "\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."

这是示例的输出。

nowdoc 的指定方式与 Heredoc 相似,但是在 nowdoc 内部未进行任何解析。 nowdoc 的标识与 Heredocs 所使用的序列相同&lt;&lt;&lt;,但是后面的标识符用单引号引起来,例如 < < <‘TEXT’。

nowdoc.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;

echostr, "\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.

这是nowdoc.php脚本的输出。

PHP 插值

变量被插入双引号中的字符串中。

interpolation.php

<?php

quantity = 5;

echo "There arequantity roses in the vase\n";

$quantity变量将在字符串输出中替换为其值。

$ php interpolation.php 
There are 5 roses in the vase

这是interpolation.php脚本的输出。

当变量名称位于另一个字符旁边时,可以使用大括号。

curlybraces.php

<?php

quantity = 5;item_name = "rose";

echo "There are quantity {item_name}s in the vase\n";

没有花括号,PHP 解释器将查找$ item_names 变量,该变量不存在。

$ php curlybraces.php 
There are 5 roses in the vase

这是curlybraces.php脚本的输出。

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是控制字符,用于将行尾返回到行首。

strophe.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 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> echo "Towering\tinferno\n";
Towering        inferno

水平选项卡在文本之间放置一个空格。

"Johnie's dog"
'Johnie\'s dog'

单引号和双引号可以嵌套。 或者,如果仅使用单引号,则可以使用反斜杠来转义单引号的默认含义。

backslash.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.\"
";

echotext;

在此示例中,我们有一个多行文本,其中包括直接语音。 双引号用反斜杠字符转义。

php> var = 233;
php> echo "var";
233
php> echo "\var isvar";
$var is 233

美元符号$在 PHP 中也有特殊含义; 它表示一个变量。 如果在字符串中使用了变量,则会对其进行插值,即使用变量的值。 为了回显变量名,我们转义了$字符\$

PHP 字符串操作

PHP 具有大量有用的有用内置函数,可用于处理字符串。

echo strlen("Eagle"); # prints 5
echo strtoupper("Eagle"); # prints EAGLE
echo strtolower("Eagle"); # prints eagle

在这里,我们使用三个功能。 strlen()函数返回字符串中的许多字符。 strtoupper()将字符转换为大写字母,strtolower()将字符转换为小写字母。

letters.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 arelength characters.\n";
echo "There are alphas alphabetic characters.\n";
echo "There aredigits 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.

这是letters.php脚本的输出。

接下来,我们介绍substr()功能。

echo substr("PHP language", 0, 3); # prints PHP
echo substr("PHP language", -8); # prints language

该函数返回字符串的一部分。 第一个参数是指定的字符串。 第二个参数是子字符串的开头。 第三个参数是可选的。 它是返回的子字符串的长度。 默认值为返回到字符串末尾。

str_repeat()函数将字符串重复指定的次数。

repeat.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 repeat.php 
##################
Project Neurea
Priority high
Security maximum
##################

这是repeat.php脚本的输出。

在下一个示例中,我们将随机修改一个字符串。

shuffling.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 shuffling.php 
ZtCeoed
eodtCZe
toZeeCd
oCdeteZ
edtCZoe
tdeCeoZ
oeZdteC

这是shuffling.php脚本的示例输出。

explode()功能用于将字符串分成多个部分。 它返回一个分割字符串部分的数组。

exploding.php

<?php

nums = "1,2,3,4,5,6,7,8,9,10,11";vals = explode(",", nums);len = count(vals);

echo "There arelen numbers in the string\n";

字符串中包含整数,并用逗号分隔。 我们计算整数的数量。

$vals = explode(",", $nums);

在这里,我们使用explode()功能分割文本。 每当找到点,字符时,该函数就会将其切成小段。

$ php exploding.php 
There are 11 numbers in the string

示例的输出。

teams1.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 teams1.php
Ajax Amsterdam - Inter Milano 2:3
Real Madridi - AC Milano 3:3
Dortmund - Sparta Praha 2:1

输出不是最佳的。 我们将对其进行更改,以使其看起来更整洁。

teams2.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 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

site = "zetcode.com";

for (i=0; isite); 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 codeo\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

这是array_of_chars.php示例的输出。

PHP 字符串格式化

字符串格式化或字符串插值是将各种值动态地放入字符串中。

fruits.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.

在下一个示例中,我们传递一个 float 和一个字符串值。

height.php

<?php

printf("Height: %f %s\n", 172.3, "cm");

浮点值的格式说明符为%f,字符串为%s

$ php height.php 
Height: 172.300000 cm

我们可能不喜欢上面示例中的数字默认情况下具有 6 个小数位的事实。 我们可以控制格式说明符中的小数位数。

height2.php

<?php

printf("Height: %.1f %s\n", 172.3, 'cm');

小数点后跟一个整数控制小数位数。 在我们的例子中,数字恰好有一位小数。

$ php height2.php 
Height: 172.3 cm

下面的示例显示其他格式设置选项。

formatting.php

<?php

# hexadecimal
printf("%x\n", 300);

# octal
printf("%o\n", 300);

# scientific
printf("%e\n", 300000);

第一种格式适用于十六进制数字。 x字符以十六进制格式格式化数字。 o字符以八进制格式显示数字。 e字符以科学格式显示数字。

$ php formatting.php 
12c
454
3.000000e+5

下一个示例显示三列数字。

columns.php

<?php

foreach (range(1,11) as num) {
    echonum , " ", 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

为了解决这个问题,我们使用宽度说明符。 宽度说明符定义对象的最小宽度。 如果对象小于宽度,则将填充空格。

columns2.php

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程