字符串(一)

2016-08-23


概述

PHP中的字符串指的是字符的序列,当我们从某一个文件中读取数据或者把数据输出到Web浏览器的时候,其中的数据就表现为字符串。
PHP字符串可以通过三种方式来初始化:单引号、双引号和使用“here document(heredoc)”形式。

单引号

在使用单引号字符串时,字符串中需要转义的特殊字符只有反斜杠和单引号本身。因为PHP不会检查单引号字符串中的插入变量及任何转义序列,所以用这种方式定义字符串不加只管而且速度快。

【例1-1】单引号字符串

<?php
print 'I have gone to the store.';

print 'I\'ve gone to store.';
//如果“ ' ”前不加反斜杠,会报错。Parse error: syntax error, unexpected 've' (T_STRING) 。

print 'Would you pay $1.75 for 8 ounces(盎司) of tap water?';

print 'In double-quoted strings, newline is represented by \n';

//输出的结果:

I have gone to the store.

I've gone to the store.

Would you pay $1.75 for 8 ounces of tap water?

In double-quoted strings, newline is represented by \n;
?>
双引号字符串

双引号字符串虽然不能识别转义的单引号,但是却能识别插入的变量和下列几种转义序列。
转义序列——-字符
\n————–>换行符(ASCII码10)
\t————–>制表符(ASCII码9)
\—————>反斜杠
\0至\777 —–>八进制数值
\x0至\xFF—–>十六进制数值

【例题1-2】双引号字符串

<?php
print 'I've gone to the store.';

$cost='$10.25';

print "The sauce cost $cost.";

print "The sauce cost \$\061\060.\x32\x35";

//输出结果

I've gone to the store.

The sauce cost $10.25.

The sauce cost $10.25.
?>
heredoc定义字符串

heredoc定义的字符串可以识别所有的插入变量以及双引号字符串能识别的转义序列,却不要求对双引号进行转义。
Heredoc以<<<加一个记号(不能使用空行或者带有空格后缀)来定义字符串的开始,并以该记号后跟一个分号(如果的话)识别字符串的结尾,以结束heredoc定义。

【例题1-3】用heredoc定义多行字符串

<?PHP
print <<< END
It's funny when signs say things like:
Original "Root" Beer
"Free" Gift
Shoes cleaned while "you" wait
or have other misquoted words.
END;
?>
//输出结果
It's funny when signs say things like:
Original "Root" Beer
"Free" Gift
Shoes cleaned while "you" wait
or have other misquoted words.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值