zoukankan      html  css  js  c++  java
  • PHP str_replace() 函数的常见用法

    <?php
    /*Function:
    	mixed str_replace ( mixed search, mixed replace, mixed subject [, int &count] )
    */
    
    //1==>
    // 输出: <body text='black'>
    /*
    	这应该是最常见的用法了,从"<body text='%body%'>"中找到"%body%",然后替换成"black"
    */
    $bodytag = str_replace("%body%", "black", "<body text='%body%'>");
    
    //2==>
    // 输出: Hll Wrld f PHP
    /*
    	参数 search 为数组的用法,逐个地遍历数组来进行替换
    */
    $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
    $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
    
    //3==>
    // 输出: You should eat pizza, beer, and ice cream every day
    /*
    	参数 search 和 replace 均为数组的用法,且数组元素的个数相同,进行相互对应的替换
    */
    $phrase  = "You should eat fruits, vegetables, and fiber every day.";
    $healthy = array("fruits", "vegetables", "fiber");
    $yummy = array("pizza", "beer", "ice cream");
    $newphrase = str_replace($healthy, $yummy, $phrase);
    
    //4==>
    // Use of the count parameter is available as of PHP 5.0.0
    /*
    	输出匹配次数
    */
    $str = str_replace("ll", "", "good golly miss molly!", $count);
    echo $count; // 2
    
    //5==>
    // Order of replacement 
    /*
    	自定义替换顺序,防止重复替换
    */
    $str       = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
    $order    = array("\r\n", "\n", "\r");
    $replace = '<br />';
    // Processes \r\n's first so they aren't converted twice. 
    $newstr = str_replace($order, $replace, $str);
    
    //6==>
    /*
    	这个是需要注意的,参数 search 和 replace 均为数组,第一次先替换 'a' ,结果为 'apple p',第二次接着替换 'p',因此会出现结果 'apearpearle pear'
    */
    // Outputs: apearpearle pear
    $letters  = array('a', 'p');
    $fruit     = array('apple', 'pear');
    $text     = 'a p';
    $output  = str_replace($letters, $fruit, $text);
    echo $output; 
    ?> 
    


  • 相关阅读:
    【初入职场】工作一个月
    sql中更新数据库用到declare @a in
    Mac 下ll命令 command not found
    GLIBC_2.7升级
    PHP 5.5以后加速插件:Zend Opcache
    ssh的public key的使用
    apache Alias使用问题
    linux下telnet mysql的3306断口,提示Can't connect to MySQL server on localhost (110)
    知乎技术方案初探[转]
    JS刷新父窗口的几种方式
  • 原文地址:https://www.cnblogs.com/catprayer/p/1777468.html
Copyright © 2011-2022 走看看