String 字符串
一、语法
一个字符串可以用 4 种方式表达:
- 单引号
- 双引号
- heredoc
- nowdoc
单引号
<?php
echo 'this is a simple string
You can also have embedded newlines in
strings this way as it is
okay to do';
?>
双引号
<?php
echo "这是双引号,里面可以放一些转义字符";
?>
heredoc
<?php
$heredocStr = <<<hello
this is a example for heredoc
hello;
?>
<?php
$heredocStr = <<<"hello"
this is a example for heredoc
hello;
?>
结尾的标志hello必须另起一行,分号结尾。
当做参数传递,初始化静态变量,类的属性和常量
nowdoc
<?php
$str = <<<'now'
Example of string
spanning multiple lines
using nowdoc syntax.
now;
?>
heredoc类似于双引号,nowdoc类似于单引号。
二、变量的输出
1、(简单)$value
<?php
$juice = "apple";
echo "He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
?>
2、 (复杂) {$value}
<?php
// 显示所有错误
error_reporting(E_ALL);
$great = 'fantastic';
// 无效,输出: This is { fantastic}
echo "This is { $great}";//$和{不能有空格
// 有效,输出: This is fantastic
echo "This is {$great}";
echo "This is ${great}";
// 有效
echo "This square is {$square->width}00 centimeters broad.";
// 有效,只有通过花括号语法才能正确解析带引号的键名
echo "This works: {$arr['key']}";
// 有效
echo "This works: {$arr[4][3]}";
// 这是错误的表达式,因为就象 $foo[bar] 的格式在字符串以外也是错的一样。
// 换句话说,只有在 PHP 能找到常量 foo 的前提下才会正常工作;这里会产生一个
// E_NOTICE (undefined constant) 级别的错误。
echo "This is wrong: {$arr[foo][3]}";
// 有效,当在字符串中使用多重数组时,一定要用括号将它括起来
echo "This works: {$arr['foo'][3]}";
// 有效
echo "This works: " . $arr['foo'][3];
echo "This works too: {$obj->values[3]->name}";
echo "This is the value of the var named $name: {${$name}}";
echo "This is the value of the var named by the return value of getName(): {${getName()}}";
echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
// 无效,输出: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>
三、存取和修改字符串中的字符
字符串也有类似于数组下标的功能。
<?php
// 取得字符串的第一个字符
$str = 'This is a test.';
$first = $str[0];
// 取得字符串的第三个字符
$third = $str[2];
// 取得字符串的最后一个字符
$str = 'This is still a test.';
$last = $str[strlen($str)-1];
/ / 修改字符串的最后一个字符
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';
?>