什么是 PHP 中的字符串

字符串是字母、数字、特殊字符和算术值或所有值的组合的序列。创建字符串的最简单方法是将字符串文字(即字符串字符)括在单引号 (') 中,如下所示:

$my_string = 'Hello World';

您也可以使用双引号 (”)。但是,单引号和双引号的工作方式不同。用单引号括起来的字符串几乎按字面意思处理,而用双引号分隔的字符串将变量替换为其值的字符串表示形式,并专门解释某些转义序列。

转义序列替换是:

  • \n替换为换行符
  • \r替换为回车符
  • \t替换为制表符
  • \$替换为美元符号本身 ($)
  • \"替换为单个双引号 (")
  • \\替换为单个反斜杠 (\)

下面是一个示例来阐明单引号字符串和双引号字符串之间的区别:

<?php
$my_str = 'World';
echo "Hello, $my_str!<br>";      // Displays: Hello World!
echo 'Hello, $my_str!<br>';      // Displays: Hello, $my_str!
echo '<pre>Hello\tWorld!</pre>'; // Displays: Hello\tWorld!
echo "<pre>Hello\tWorld!</pre>"; // Displays: Hello   World!
echo 'I\'ll be back';            // Displays: I'll be back
?>

操作 PHP 字符串

PHP 提供了许多用于操作字符串的内置函数,例如计算字符串的长度、查找子字符串或字符、用不同的字符替换字符串的一部分、将字符串分开等等。以下是其中一些函数的示例。

计算字符串的长度

该函数用于计算字符串内的字符数。它还包括字符串内的空格。strlen()

<?php
$my_str = 'Welcome to Tutorial Republic';
// Outputs: 28
echo strlen($my_str);
?>

计算字符串中的单词数

该函数计算字符串中的单词数。str_word_count()

<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';
// Outputs: 9
echo str_word_count($my_str);
?>

替换字符串中的文本

这将替换目标字符串中出现的所有搜索文本。str_replace()

<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
// Display replaced string
echo str_replace("facts", "truth", $my_str);
?>

上述代码的输出将是:

If the truth do not fit the theory, change the truth.

您可以选择将第四个参数传递给函数,以了解执行了多少次字符串替换,如下所示。str_replace()

<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
// Perform string replacement
str_replace("facts", "truth", $my_str, $count);
// Display number of replacements performed
echo "The text was replaced $count times.";
?>

上述代码的输出将是:

The text was replaced 2 times.

反转字符串

该函数反转字符串。strrev()

<?php
$my_str = 'You can do anything, but not everything.';
// Display reversed string
echo strrev($my_str);
?>

上述代码的输出将是:

.gnihtyreve ton tub ,gnihtyna od nac uoY

PHP 字符串参考

有关有用的字符串函数的完整列表,请查看 PHP 字符串参考。

最后修改:2024 年 09 月 07 日
如果觉得我的文章对你有用,请随意赞赏