代码改变世界

第四章 字符串操作与正则表达式(2)

2016-07-26 21:36  yojiaku  阅读(446)  评论(0编辑  收藏  举报

4.2 字符串的格式化

  字符串的整理:chop() , ltrim() , trim()

  整理字符串的第一步是清理字符串中多余的空格。

  下面依旧以上一篇用到的例子,逐步完善,第一步:

$name = $_POST['name'];
$email = $_POST['email'];
$feedback = $_POST['feedback'];

  我们可以用trim()来整理用户输入的数据,即将上面的代码改为:

$name = trim($_POST['name']);
$email = trim($_POST['email']);
$feedback = trim($_POST['feedback']);

  trim()函数可以去除字符串开始位置和结束位置的空格,并将结果字符串返回:string trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] )

  其有两个参数,第一个必选,第二个可选,若没有写第二个参数,则默认情况下是去除字符串中的换行符(\n)和回车符(\r),水平和垂直制表符(\t & \x0B)、字符串结束符(\0)和空格;若有第二个参数,则去掉此参数代表的字符。而ltrim()从字符串左边除去空格,rtrim()从字符串右边除去空格。

  chop():removes the last character in the string(去掉字符串最后的字母)。

 

  格式化字符串以便显示:

  1.使用HTML格式化:nl2br()函数--string nl2br ( string $string [, bool $is_xhtml = true ] )

   直接使用"\n"在浏览器中是不会显示出效果的,举例:

echo "hello \n php";

    像这样写的效果图是:

    所以我们使用nl2br()函数:

#nl2br()
echo nl2br("hello \n php");

   结果:

  2.为打印输出而格式化字符串

  到现在为止,我们多使用echo语言结构将字符串输出到浏览器。PHP也支持print()结构,它的功能与echo一样,但具有返回值(true或false)。

  print():int print ( string $arg ),准确来说,返回值一定是1.

      举例:

#print()
print("Hello World");

print "print() also works without parentheses.";

print "This spans
multiple lines. The newlines will be
output as well";

    输出结果为:

    除print之外,还有printf()和sprintf()

  printf():int printf ( string $format [, mixed $args [, mixed $... ]] ),返回值是这个字符串的长度(Returns the length of the outputted string)。

      (这里与书上讲的有出入,书上讲的是void)

  sprintf():string sprintf ( string $format [, mixed $args [, mixed $... ]] ),返回一个格式化了的字符串。

  传递给这两个函数的第一个参数都是字符串格式,它们使用格式代码而不是变量来描述输出字符串的基本形状。(这里的语法可以参考C语言)

  

  3.改变字符串中的字母大小写

  strtoupper():将字符串全部转换为大写

  strtolower():将字符串全部转换为小写

  ucfirst():如果字符串的第一个字符是字母,就将该字母转换为大写

  ucwords():将字符串每个单词的第一个字母转换为大写

 

  4.格式化字符串以便存储:addslashes() & stripslashes()

  对于引号、反斜杠(\)、NULL字符,将它们插入数据库中的时候,数据库会将这些字符解释成控制符,我们就需要将它们进行转义,以便使像MySQL这样的数据库能够理解我们表示的是有实际意义的特殊文本字符,而不是控制序列。

  转义方法:

    1,使用反斜杠(\)--对所有特殊字符都管用

    2,addslashes()函数:string addslashes ( string $str )。调用这个函数后,所有引号都会被加上反斜杠,例如:

#addslashes()
$str = "Is your name O'Reilly?";
echo addslashes($str);

    结果:

    3,striplashes()函数:string stripcslashes ( string $str )。调用这个函数后,会移除反斜杠,例如:

#addslashes()
$str = "Is your name O'Reilly?";
echo addslashes($str);
echo "<br />";
#stripcslashes()
echo stripcslashes($str);

    结果: