Home Backend Development PHP Problem What are the ways to define php strings?

What are the ways to define php strings?

Jun 30, 2022 pm 07:06 PM
php php string

有4种定义方式:1、用单引号包裹字符,语法“'字符内容'”;2、用双引号包裹字符,语法“"字符内容"”;3、用heredoc结构,语法“

What are the ways to define php strings?

本教程操作环境:windows7系统、PHP8.1版、DELL G3电脑

字符串是连续的字符序列,在其它语言中,字符和字符串是两种不同的数据类型,但在 PHP 中,统一将字符和字符串当作字符串数据类型。

在 PHP 中,定义字符串有4种方式,分别是单引号方式、双引号方式、Heredoc 方式、nowdoc 方式。

“单引号”定义方式

定义一个字符串的最简单的方法是用单引号把它包围起来(字符 ')。

要表达一个单引号自身,需在它的前面加个反斜线(\)来转义。要表达一个反斜线自身,则用两个反斜线(\\)。其它任何方式的反斜线都会被当成反斜线本身:也就是说如果想使用其它转义序列例如 \r 或者 \n,并不代表任何特殊含义,就单纯是这两个字符本身。

注意: 不像双引号和 heredoc 语法结构,在单引号字符串中的变量和特殊字符的转义序列将不会被替换。

示例:

<?php
echo &#39;this is a simple string&#39;;
echo &#39;<br>&#39;;

// 可以录入多行
echo &#39;You can also have embedded newlines in
strings this way as it is
okay to do&#39;;
echo &#39;<br>&#39;;

// 输出: Arnold once said: "I&#39;ll be back"
echo &#39;Arnold once said: "I\&#39;ll be back"&#39;;
echo &#39;<br>&#39;;

// 输出: You deleted C:\*.*?
echo &#39;You deleted C:\\*.*?&#39;;
echo &#39;<br>&#39;;

// 输出: You deleted C:\*.*?
echo &#39;You deleted C:\*.*?&#39;;
echo &#39;<br>&#39;;

// 输出: This will not expand: \n a newline
echo &#39;This will not expand: \n a newline&#39;;
echo &#39;<br>&#39;;

// 输出: Variables do not $expand $either
echo &#39;Variables do not $expand $either&#39;;
echo &#39;<br>&#39;;
?>
Copy after login

What are the ways to define php strings?

“双引号”定义方式

如果字符串是包围在双引号(")中, PHP 将对以下特殊的字符进行解析:

转义字符
序列含义
\n换行(ASCII 字符集中的 LF 或 0x0A (10))
\r回车(ASCII 字符集中的 CR 或 0x0D (13))
\t水平制表符(ASCII 字符集中的 HT 或 0x09 (9))
\v垂直制表符(ASCII 字符集中的 VT 或 0x0B (11))
\eEscape(ASCII 字符集中的 ESC 或 0x1B (27))
\f换页(ASCII 字符集中的 FF 或 0x0C (12))
\\反斜线
\$美元标记
\"双引号
\[0-7]{1,3}符合该正则表达式序列的是一个以八进制方式来表达的字符,which silently overflows to fit in a byte (e.g. "\400" === "\000")
\x[0-9A-Fa-f]{1,2}符合该正则表达式序列的是一个以十六进制方式来表达的字符
\u{[0-9A-Fa-f]+}匹配正则表达式的字符序列是 unicode 码位, 该码位能作为 UTF-8 的表达方式输出字符串

和单引号字符串一样,转义任何其它字符都会导致反斜线被显示出来。

用双引号定义的字符串最重要的特征是变量会被解析,即变量解析。

示例:

<?php
echo "this is a simple string";
echo "<br>";

// 也可以录入多行
echo "You can also have embedded newlines in
strings this way as it is
okay to do";
?>
Copy after login

What are the ways to define php strings?

“Heredoc”定义方式

第三种表达字符串的方法是用 heredoc 句法结构:<<<。在该运算符之后要提供一个标识符,然后换行。接下来是字符串 string 本身,最后要用前面定义的标识符作为结束标志。

结束标识符可以使用空格或制表符(tab)缩进,此时文档字符串会删除所有缩进。 在 PHP 7.3.0 之前的版本中,结束时所引用的标识符必须在该行的第一列。

而且,标识符的命名也要像其它标签一样遵守 PHP 的规则:只能包含字母、数字和下划线,并且必须以字母和下划线作为开头。

<?php
$str = <<<EOF
  url:
  https://www.php.cn/
EOF;
echo $str;
?>
Copy after login

What are the ways to define php strings?

PHP 7.3.0 之后的基础 Heredoc 示例

<?php
// 无缩进
echo <<<END
      a
     b
    c
\n
END;
// 4 空格缩进
echo <<<END
      a
     b
    c
    END;
Copy after login

What are the ways to define php strings?

如果结束标识符的缩进超过内容的任何一行的缩进,则将抛出 ParseError 异常:

示例:结束标识符的缩进不能超过正文的任何一行

<?php
echo <<<END
  a
 b
c
   END;
Copy after login

以上例程在 PHP 7.3 中的输出:

PHP Parse error:  Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4
Copy after login

制表符也可以缩进结束标识符,但是,关于缩进结束标识符和内容, 制表符和空格不能混合使用。在以上任何情况下, 将会抛出 ParseError 异常。 之所以包含这些空白限制,是因为混合制表符和空格来缩进不利于易读性。

示例:内容(空白)和结束标识符的不同缩进

<?php
// 以下所有代码都不起作用。
// 正文(空格)和结束标记(制表符),不同的缩进
{
    echo <<<END
     a
        END;
}
// 在正文中混合空格和制表符
{
    echo <<<END
        a
     END;
}
// 在结束标记中混合空格和制表符
{
    echo <<<END
          a
         END;
}
Copy after login

以上例程在 PHP 7.3 中的输出:

PHP Parse error:  Invalid indentation - tabs and spaces cannot be mixed in example.php line 8
Copy after login

内容字符串的结束标识符后面不需要跟分号或者换行符。 例如,从 PHP 7.3.0 开始允许以下代码:

示例:在结束标识符后继续表达式

<?php
$values = [<<<END
a
  b
    c
END, &#39;d e f&#39;];
var_dump($values);
Copy after login

以上例程在 PHP 7.3 中的输出:

array(2) {
  [0] =>
  string(11) "a
  b
    c"
  [1] =>
  string(5) "d e f"
}
Copy after login

“Nowdoc”定义方式

就象 heredoc 结构类似于双引号字符串,Nowdoc 结构是类似于单引号字符串的。Nowdoc 结构很象 heredoc 结构,但是 nowdoc 中不进行解析操作。这种结构很适合用于嵌入 PHP 代码或其它大段文本而无需对其中的特殊字符进行转义。与 SGML 的 结构是用来声明大段的不用解析的文本类似,nowdoc 结构也有相同的特征。

一个 nowdoc 结构也用和 heredocs 结构一样的标记 <<<, 但是跟在后面的标识符要用单引号括起来,即 <<<'EOT'。Heredoc 结构的所有规则也同样适用于 nowdoc 结构,尤其是结束标识符的规则。

示例:

<?php
echo <<<&#39;EOD&#39;
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \&#39;.
EOD;
Copy after login

What are the ways to define php strings?

<?php

/* 含有变量的更复杂的示例 */
class foo
{
    public $foo;
    public $bar;

    function __construct()
    {
        $this->foo = &#39;Foo&#39;;
        $this->bar = array(&#39;Bar1&#39;, &#39;Bar2&#39;, &#39;Bar3&#39;);
    }
}

$foo = new foo();
$name = &#39;MyName&#39;;

echo <<<&#39;EOT&#39;
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital &#39;A&#39;: \x41
EOT;
?>
Copy after login

What are the ways to define php strings?

注意:

Nowdoc 结构是在 PHP 5.3.0 中加入的。

扩展知识:变量解析

当字符串用双引号或 heredoc 结构定义时,其中的变量将会被解析。

这里共有两种语法规则:一种简单规则,一种复杂规则。简单的语法规则是最常用和最方便的,它可以用最少的代码在一个 string 中嵌入一个变量,一个 array 的值,或一个 object 的属性。

复杂规则语法的显著标记是用花括号包围的表达式。

简单语法

当 PHP 解析器遇到一个美元符号($)时,它会和其它很多解析器一样,去组合尽量多的标识以形成一个合法的变量名。可以用花括号来明确变量名的界线。

<?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.";
// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of ${juice}s.";
?>
Copy after login

What are the ways to define php strings?

类似的,一个 array 索引或一个 object 属性也可被解析。数组索引要用方括号(])来表示索引结束的边际,对象属性则是和上述的变量规则相同。

<?php
$juices = array("apple", "orange", "koolaid1" => "purple");

echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;

class people {
    public $john = "John Smith";
    public $jane = "Jane Smith";
    public $robert = "Robert Paulsen";

    public $smith = "Smith";
}

$people = new people();

echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john&#39;s wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won&#39;t work
?>
Copy after login

What are the ways to define php strings?

从 PHP 7.1.0 起,还支持负数字索引。

<?php
$string = &#39;string&#39;;
echo "The character at index -2 is $string[-2].", PHP_EOL;
$string[-3] = &#39;o&#39;;
echo "Changing the character at index -3 to o gives $string.", PHP_EOL;
?>
Copy after login

What are the ways to define php strings?

如果想要表达更复杂的结构,请用复杂语法。

复杂(花括号)语法

复杂语法不是因为其语法复杂而得名,而是因为它可以使用复杂的表达式。

任何具有 string 表达的标量变量,数组单元或对象属性都可使用此语法。 表达式的书写方式与在 string 以外的方式相同, 然后用花括号 { 和 } 把它括起来即可。由于 { 无法被转义,只有 $ 紧挨着 { 时才会被识别。可以用 {\$ 来表达 {$。下面的示例可以更好的解释:

<?php
// 显示所有错误
error_reporting(E_ALL);

$great = &#39;fantastic&#39;;

// 无效,输出: This is { fantastic}
echo "This is { $great}";

// 有效,输出: This is fantastic
echo "This is {$great}";

// 有效
echo "This square is {$square->width}00 centimeters broad.";

// 有效,只有通过花括号语法才能正确解析带引号的键名
echo "This works: {$arr[&#39;key&#39;]}";

// 有效
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[&#39;foo&#39;][3]}";

// 有效
echo "This works: " . $arr[&#39;foo&#39;][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()}";

// 无效, 输出: C:\folder\{fantastic}.txt
echo "C:\folder\{$great}.txt"
// 有效, 输出: C:\folder\fantastic.txt
echo "C:\\folder\\{$great}.txt"
?>
Copy after login

也可以在字符串中用此语法通过变量来调用类的属性。

<?php
class foo {
    var $bar = &#39;I am bar.&#39;;
}

$foo = new foo();
$bar = &#39;bar&#39;;
$baz = array(&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;, &#39;quux&#39;);
echo "{$foo->$bar}\n";
echo "{$foo->{$baz[1]}}\n";
?>
Copy after login

What are the ways to define php strings?

注意:

函数、方法、静态类变量和类常量可使用 {$} ,在该字符串被定义的命名空间中将其值作为变量名来访问。只单一使用花括号 ({}) 无法处理从函数或方法的返回值或者类常量以及类静态变量的值。

推荐学习:《PHP视频教程

The above is the detailed content of What are the ways to define php strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles