ea php字符串是一系列字符,即用于存储和处理文本。 在php中有4
种方法可用于指定字符串。
我们可以通过在单引号中包含文本在php中创建一个字符串。 这是在php中指定字符串的最简单的方法。如下一个示例 -
<?php
$str='hello text within single quote';
echo $str;
?>
上面代码执行结果如下 -
hello text within single quote
我们可以在单个引用的php字符串中存储多行文本,特殊字符和转义序列。
<?php
$str1='hello text
multiple line
text within single quoted string';
$str2='using double "quote" directly inside single quoted string';
$str3='using escape sequences \n in single quoted string';
echo "$str1 <br/> $str2 <br/> $str3";
?>
输出结果如下 -
hello text multiple line text within single quoted string
using double "quote" directly inside single quoted string
using escape sequences \n in single quoted string
注意:在单引号php字符串中,大多数转义序列和变量不会被解释。 可以使用单引号
\'
反斜杠和通过\\
在单引号引用php字符串。
参考下面实例代码 -
<?php
$num1=10;
$str1='trying variable $num1';
$str2='trying backslash n and backslash t inside single quoted string \n \t';
$str3='using single quote \'my quote\' and \\backslash';
echo "$str1 <br/> $str2 <br/> $str3";
?>
输出结果如下-
trying variable $num1
trying backslash n and backslash t inside single quoted string \n \t
using single quote 'my quote' and \backslash
在php中,我们可以通过在双引号中包含文本来指定字符串。 但转义序列和变量将使用双引号php字符串进行解释。
<?php
$str="hello text within double quote";
echo $str;
?>
上面代码执行输出结果 -
hello text within double quote
`
现在,不能使用双引号直接在双引号字符串内。
<?php
$str1="using double "quote" directly inside double quoted string";
echo $str1;
?>
上面代码执行输出结果 -
parse error: syntax error, unexpected 'quote' (t_string) in d:\wamp\www\string1.php on line 2
`
我们可以在双引号的php字符串中存储多行文本,特殊字符和转义序列。参考如下代码 -
<?php
$str1="hello text
multiple line
text within double quoted string";
$str2="using double \"quote\" with backslash inside double quoted string";
$str3="using escape sequences \n in double quoted string";
echo "$str1 <br/> $str2 <br/> $str3";
?>
上面代码执行输出结果 -
hello text multiple line text within double quoted string
using double "quote" with backslash inside double quoted string
using escape sequences in double quoted string
`
在双引号字符串中,变量将会被解释,这是因为我们对特殊字符进行了转义。
<?php
$num1=10;
echo "number is: $num1";
?>
上面代码输出结果为 -
number is: 10