本文实例讲述了PHP常见字符串操作函数与用法。分享给大家供大家参考,具体如下:
一、字符串的格式化
1、字符串的格式化
trim()函数可以去除字符串的开始位置和结束位置的空格,并将结果字符串返回,默认情况下去除的字符是换行符和回车符(\n和\r),水平和垂直制表符(\t和X0B)
ltrim()函数只从字符的开始处(左边)去除空格
rtrim()函数只从函数的结束处(右边)去除空格
2、格式化字符串以便显示
①使用HTML格式化:n12br()函数
在字符串中的新行(\n)之前插入换行符
<?php
echo nl2br("One line.\nAnother line.");
?>
结果
One line.
Another line.
②为打印输出而格式化字符串
printf()结构
$s="world");
printf("Hello %s",$s);
3.改变字符串中的字母大小写
| 函数 | 描述 | 使用 $subject=Hello World | 返回值 | 
|---|---|---|---|
| strtoupper() | 将字符串转为大写 | strtoupper($subject ) | HELLO WORLD | 
| strtolower() | 将字符串转为小写 | strtolower($subject ) | hello world | 
| ucfirst() | 如果字符串第一个字符是字符,将其转为大写 | ucfirst($subject ) | Hello world | 
| ucwords() | 将字符串的每个单词的首字母大写 | ucwords($subject ) | Hello World | 
二、用字符串函数连接和分割字符串
1、用函数explode()、implode()和join()
exlpode()
把字符串打散为数组:
<!DOCTYPE html>
<html>
<body>
<?php
$str = "Hello world. I love Shanghai!";
print_r (explode(" ",$str));
?>
</body>
</html>
结果
Array ( [0] => Hello [1] => world. [2] => I [3] => love [4] => Shanghai! )
implode()  (jion()是implode()函数的别名)
把数组元素组合为字符串:
<!DOCTYPE html>
<html>
<body>
<?php
$arr = array('Hello','World!','I','love','Shanghai!');
echo implode(" ",$arr);
?>
</body>
</html>
      内容版权声明:除非注明,否则皆为本站原创文章。
