日期:2014-05-17  浏览次数:20563 次

PHP开发笔记系列(二)-字符串使用
   
    经过了《PHP开发笔记系列(一)-PDO使用》,今天开了关于PHP开发中字符串的处理,《PHP开发笔记系列(二)-字符串使用》,形成《PHP开发笔记系列》的第二篇。

    字符串是任何开发语言都必须处理的,在PHP中字符串可以使用单引号(')或双引号(")进行定义。那单引号和双引号不同之处在哪?那就是双引号中的变量会被变量值替换,而单引号中的内容将原样输出。下面将日常程序开发中会碰到的字符串处理场景整理。


1. 以数组形式访问字符串(strlen)
file:str-lengh.php
url:http://localhost:88/str/str-lengh.php
<?php
    $word = 'Hello, Ryan!';
    echo "String($word)'s length: ".strlen($word)."<br/>";
    
    // for循环访问数组
    //for($i=0; $i<strlen($word); $i++){
    //    echo $word[$i],"<br/>";
    //}
    
    // while循环访问数组
    $i=0;
    while($i<strlen($word)){
         echo $word[$i],"<br/>";
         $i++
    }
?>

2. 去除文本中的所有HTML标记(strip_tags)
file:str-strip-tags.php
url:http://localhost:88/str/str-strip-tags.php
<?php
    // 字符串中的所有html标签都闭合
    $text = "<h1>hello world!</h1><h1>hello world!</h1><h1>hello world!</h1>";
    
    // 输出原始的字符串内容
    echo "Original Text:";
    echo $text."<br/>";
    
    // 去除所有html标签后进行输出
    echo "Destination Text(After strip_tags)"."<br/>";
    echo strip_tags($text)."<br/>";

    // 字符串中的html标签不闭合
    $text = "<h1>hello world!";
    
    // 去除所有html标签后进行输出
    echo "Original Text:";
    echo $text."<br/>";
    
    // 去除所有html标签后进行输出
    echo "Destination Text(After strip_tags)"."<br/>";
    echo strip_tags($text)."<br/>";
?>

    备注:如果$text的值是<h1>hello world!,少了</h1>,那么<h1>将不会被strip_tags函数去除,从而影响后面的格式输出,使后续的所有输出都有h1标题的样式。

3. 转义html实体(rawurlencode)
file:str-entities.php
url:http://localhost:88/str/str-entities.php
<?php
    $text = "hello & world!";
    
    echo $text."<br/>";
    
    echo rawurlencode($text)."<br/>";
?>


4. 强制文本折行显示(wordwrap)
    wordwrap函数可以按照指定的字符串折行长度,将长文本进行折行。
file:str-wordwrap.php
url:http://localhost:88/str/str-wordwrap.php
<?php
    $text = "This document covers the JavaTM 2 Platform Standard Edition 5.0 Development Kit (JDK 5.0). Its external version number is 5.0 and internal version number is 1.5.0. For information on a feature of the JDK, click on its component in the diagram below.";
    
    echo "Original text:"."<br/>";
    echo $text."<br/>";
    
    echo $text."<hr/>";
    
    echo "Destination text(after wrap):"."<br/>";
    echo wordwrap($text, 50, "<br/>")."<br/>";
?>


5. 字符串定位与替换(strpos、str_replace)
    字符串定位使用strpos函数,该函数返回一个字符串在另一个字符串出现的第一个位置,类似于JAVA中String类的indexOf()方法的作用:
file:str-strpos.php
url:http://localhost:88/str/str-strpos.php
<?php
    $text = "hello world!";
    
    echo strpos($text, "e");  
?>


    字符串替换使用str_replace函数,该函数替换部分字符串中的文本,类似于JAVA中String类的replace()方法的作用:
file:str-strreplace.php
url:http://localhost:88/str/str-strreplace.php
<?php
    $text = "This document covers the JavaTM 2 Platform Standard Edition 5.0 Development Kit (JDK 5.0). Its external version number is 5.0 and internal version number is 1.5.0. For information on a feature of the JDK, click on its component in the diagram below.";
   
    echo