📜  讲解PHP的一些字符串函数

📅  最后修改于: 2022-05-13 01:56:11.868000             🧑  作者: Mango

讲解PHP的一些字符串函数

在编程世界中,字符串被认为是一种数据类型,通常是多个字符的序列,可以包含空格、数字、字符和特殊符号。例如,“Hello World!”、“ID-34#90”等PHP还允许使用单引号(' ')来定义字符串。每种编程语言都提供了一些用于操作字符串的内置函数。 PHP提供的一些基本字符串函数如下:

strlen()函数它返回字符串的长度,即字符串中所有字符的计数,包括空格字符。

句法:

strlen(string or variable name)

例子:

PHP
" . strlen("GeeksForGeeks"); 
  
?>


PHP


PHP
";
  
// Removes whitespaces from both ends
echo trim($str) . "
";    // Removes whitespaces from right end echo rtrim($str) . "
";    // Removes whitespaces from left end echo ltrim($str);    ?>


PHP
";
echo strtolower($str);
  
?>


PHP
";
print_r(str_split($str, 3));
  
?>


输出:

12
13

strrev()函数它返回给定字符串。

句法:

strrev(string or variable name)

例子:

PHP


输出
!dlroW olleH

trim() ltrim() rtrim()Chop( )功能:它从字符串中删除空格或其他字符。它们有两个参数:一个字符串和另一个 charList,它是需要省略的字符列表。

  • trim() –从两边删除字符或空格。
  • rtrim()chop() –从右侧删除字符或空格。
  • ltrim() –从左侧删除字符或空格。

注意:以下示例中给出的代码的浏览器输出可能与这些函数的 HTML 输出不同。

句法:

rtrim(string, charList)
ltrim(string, charList)
trim(string, charList)
chop(string, charList)

参数值:

  • $ 字符串:此强制参数指定要检查的字符串。
  • $charlist:此可选参数指定要从字符串中删除哪些字符。如果未提供此参数,则删除以下字符:
    • “\0” - 空
    • “\t” – 制表符
    • “\n” – 换行
    • “\x0B” – 垂直制表符
    • “\r” – 回车
    • ” “ – 普通空白

注 –参数charList仅在PHP 4.1 或更高版本中可用。

例子:

PHP

";
  
// Removes whitespaces from both ends
echo trim($str) . "
";    // Removes whitespaces from right end echo rtrim($str) . "
";    // Removes whitespaces from left end echo ltrim($str);    ?>
输出
This is an example for string functions.

This is an example for string functions.
This is an example for string functions.
This is an example for string functions.
This is an example for string functions.

strtoupper()strtolower()函数:它在改变其字母大小写后返回字符串

  • strtoupper() -将所有字母转换为大写后返回字符串。
  • strtolower() -将所有字母转换为小写后返回字符串。

句法:

strtoupper(string)
strtolower(string)

例子:

PHP

";
echo strtolower($str);
  
?>

输出:

GEEKSFORGEEKS
geeksforgeeks

str_split()函数:它返回一个包含部分字符串的数组。

句法:

str_split(string, length)

参数:

  • 字符串:指定要检查的字符串,也可以是字符串类型的变量名。
  • length:指定要存储在字符串中的字符串各部分的长度,默认为1。如果长度大于字符串的大小,则返回完整的字符串

例子:

PHP

";
print_r(str_split($str, 3));
  
?>

输出:

Array ( 
    [0] => G 
    [1] => e 
    [2] => e 
    [3] => k 
    [4] => s 
    [5] => F 
    [6] => o 
    [7] => r 
    [8] => G 
    [9] => e 
    [10] => e 
    [11] => k 
    [12] => s 
)
Array ( 
    [0] => Gee 
    [1] => ksF 
    [2] => orG 
    [3] => eek 
    [4] => s 
)