zoukankan      html  css  js  c++  java
  • php中的字符串常用函数(三) str_replace() 子字符串替换

    mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] );

    该函数返回一个字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换之后的结果。

    返回值和前三个参数都可以为字符串或数组二者其一。第四个参数指定一个变量名为替换次数。


    例1:参数全部为字符串。

    $bodytag  =  str_replace ( "%body%" ,  "black" ,  "<body text='%body%'>" );

    =>"<body text='black'>"

    例2:参数1为数组,23为字符串。

    $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U", "P", "h");
    $onlyconsonants = str_replace($vowels, "@", "Hello world of php", $count);

    =>"H@ll@ w@rld @f p@p" //这个例子的p没有被P匹配到。说明这个函数是大小写敏感的。如果需要忽略大小写可用str_ireplace()函数,用法一毛一样。

    =>$count =>5//替换了5次。分别是 e、 o、 o、 o、 h

    例3:

    $str = "Line 1
    Line 2
    Line 3
    Line 4
    ";
    $order = array("
    ", "
    ", "
    ");
    $replace = '<br/>';
    $newStr = str_replace($order, $replace, $str, $count);

    =>$count=>4//替换了4次。分别是 、 、 、 。注意,⚠️因为$order中把 写在前面所以第三次匹配没有分成两次 , 。

    例4:

    $letters  = array( 'a' ,  'p' );
    $fruit    = array( 'apple' ,  'pear' );
    $text     =  'a p' ;
    $output   =  str_replace ( $letters ,  $fruit ,  $text , $count);
    echo  $output ;
    echo  $count;

    =>猜一下会输出啥吧。例4能搞定。这个函数就可以了。

  • 相关阅读:
    [置顶] NO.4 使用预处理器进行调试
    VC用OLE方式读写Excel
    Eclipse 4.2 + Tomcat 7.x + JDK 7 搭建Java Web开发环境
    (step4.3.1) hdu 1010(Tempter of the Bone——DFS)
    linked-list-random-node
    insert-delete-getrandom-o1-duplicates-allowed
    C++中对Mysql的操作函数可以参考以下blog中的内容
    insert-delete-getrandom-o1
    kth-smallest-element-in-a-sorted-matrix
    combination-sum-iv
  • 原文地址:https://www.cnblogs.com/sweetXiaoma/p/6000283.html
Copyright © 2011-2022 走看看