如何在PHP中使用字符串(附代码示例)

1,249 阅读1分钟

你可以用这种符号来定义一个字符串:

$name = 'Flavio'; //string defined with single quotes

$name = "Flavio"; //string defined with double quotes

使用单引号和双引号的最大区别是,使用双引号,我们可以用这种方式扩展变量:

$test = 'an example';

$example = "This is $test"; //This is an example

而用双引号可以使用转义字符(想想新行\n 或制表符\t ):

$example = "This is a line\nThis is a line";

/*
output is:

This is a line
This is a line
*/

PHP在其标准库(语言默认提供的功能库)中为你提供了非常全面的功能。

首先,我们可以使用. 操作符将两个字符串连接起来:

$firstName = 'Flavio';
$lastName = 'Copes';

$fullName = $firstName . ' ' . $lastName;

我们可以用strlen() 函数来检查一个字符串的长度:

$name = 'Flavio';
strlen($name); //6

一个函数是由一个标识符(本例中为strlen )和圆括号组成的。在这些圆括号内,我们向函数传递一个或多个参数。在本例中,我们有一个参数。

该函数做一些事情,当它完成后,它可以返回一个值。在本例中,它返回数字6 。如果没有返回值,函数返回null

我们以后会看到如何定义我们自己的函数。

我们可以用substr() 来获取一个字符串的一部分:

$name = 'Flavio';
substr($name, 3); //"vio" - start at position 3, get all the rest
substr($name, 2, 2); //"av" - start at position 2, get 2 items

我们可以用str_replace() 替换一个字符串的一部分:

$name = 'Flavio';
str_replace('avio', 'ower', $name); //"Flower"

当然,我们可以将结果分配给一个新的变量:

$name = 'Flavio';
$itemObserved = str_replace('avio', 'ower', $name); //"Flower"

还有很多内置函数,你可以用来处理字符串。

这里是一个简短的、不全面的列表,只是为了向你展示各种可能性: