PHP中的string类型使用说明
前端之家收集整理的这篇文章主要介绍了
PHP中的string类型使用说明,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
注意:PHP没有对string的长度做限制。唯一限制的就是PHP在计算机中的可用内存(PHP.ini文件中的memory_limit变量的值)
限定字符串范围的方法有4中:
1、单引号;
2、双引号;
3、原型文档语法;
4、nowdoc Syntax(PHP5.3.0开始) 1、如果字符串使用单引号“‘”包裹,字符串中如果出现单引号“,”和反斜杠“\”符号,需要进行转义。
<div class="codetitle"><a style="CURSOR: pointer" data="55569" class="copybut" id="copybut55569" onclick="doCopy('code55569')"> 代码如下:
<div class="codebody" id="code55569">
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:*.
?
echo 'You deleted C:\*.?';
// Outputs: You deleted C:*.
?
echo 'You deleted C:*.?';
(有待验证 单引号包裹的字符串反斜杠是否需要转义) 2、如果字符串被双引号包裹 一下字符都会被转义:
Escaped characters Sequence Meaning
\n line
Feed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since
PHP 5.2.5)
\f form
Feed (FF or 0x0C (12) in ASCII) (since
PHP 5.2.5)
\ backslash
\$ dollar sign
\" double-quote
[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation 如果字符串 使用双引号“"”或者原形文档语法的形式包裹的话,在字符串中的变量会被解析。
1、简单语法:
因为解析器会贪婪匹配$后面的字符,所以,为了不出什么以外,应该使用"{"和"}"来表名变量的边界。
<div class="codetitle">
<a style="CURSOR: pointer" data="47283" class="copybut" id="copybut47283" onclick="doCopy('code47283')"> 代码如下: <div class="codebody" id="code47283">
<?
PHP $beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers"; // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
同样,数组的下标和对象的
属性也会不解析。
<div class="codetitle">
<a style="CURSOR: pointer" data="25256" class="copybut" id="copybut25256" onclick="doCopy('code25256')"> 代码如下: <div class="codebody" id="code25256">
<?
PHP // These examples are specific to using arrays inside of strings.
// When outside of a string,always quote array string keys and do not use
// {braces}.
// Show all errors
error_reporting(E_ALL);
$fruits = array('strawberry' => 'red','banana' => 'yellow');
// Works,but note that this works differently outside a string
echo "A banana is $fruits[banana].";
// Works
echo "A banana is {$fruits['banana']}.";
// Works,but
PHP looks for a constant named banana first,as described below.
echo "A banana is {$fruits[banana]}.";
// Won't work,use braces. This results in a parse error.
echo "A banana is $fruits['banana'].";
// Works
echo "A banana is " . $fruits['banana'] . ".";
// Works
echo "This square is $square->width meters broad.";
// Won't work. For a solution,see the complex
Syntax.
echo "This square is $square->width00 centimeters broad.";
?>