入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

替换字符串:str_replace()、substr_replace()函数

创建时间:2017-10-27 投稿人: 浏览次数:197

替换字符串:str_replace()、substr_replace()函数


进行替换操作最常用的字符串函数是str_replace()。它的函数原型如下所示:

mixed str_replace(mixed needle,mixed new_needle,mixed haystack[,int&count]));

这个函数用”new_needle”替换所有haystack中的”needle”,并且返回haystack替换后的结果。可选的第四个参数是count,它包含了要执行的替换操作次数

提示 你可以以数组的方式传递所有参数,该函数可以很好地完成替换。可以传递一个要被替换单词的数组,一个替换单词的数组,以及应用这些规则的目标字符串数组。这个函数将返回替换后的字符串数组。

例子:

<?php

    $str = "He told me:"Hello world! but I don"t have any money!"";

    $find = "He";
    $replace = "SHE";

    $ret = str_replace($find, $replace, $str,$count);
    var_dump($ret);
    var_dump($count);

输出:

string "SHE told me:"SHEllo world! but I don"t have any money!"" (length=55)

int 2
当被查找对象为字符串数组时会将数组中所有元素遍历并替换
$str = array("He told me:"Hello world! but I don"t have any money!"","He is a hero!");

$find = "He";
$replace = "SHE";

$ret = str_replace($find, $replace, $str,$count);
var_dump($ret);
var_dump($count);

输出:

array
  0 => string "SHE told me:"SHEllo world! but I don"t have any money!"" (length=55)
  1 => string "SHE is a hero!" (length=14)

int 3
find为数组replace为字符串时,会将str中所有包含find子元素的字符串都替换为$replace
$str = array("He told me:"Hello world! but I don"t have any money!"","He is a hero not me!");

$find = array("He","me");
$replace = "SHE";

$ret = str_replace($find, $replace, $str,$count);
var_dump($ret);
var_dump($count);

输出:

array
  0 => string "SHE told SHE:"SHEllo world! but I don"t have any money!"" (length=56)
  1 => string "SHE is a hero not SHE!" (length=22)

int 5
find、replace均为数组时,会将str中所有包含find子元素的字符串都与replace中的子元素一一对应进行替换,若find子元素数量大于replace子元素数量,则超出部分用“”来替换,若replace子元素数量大于$find子元素数量,则超出部分不替换
$str = array("He told me:"Hello world! but I don"t have any money!"","He is a hero not me!");

$find = array("He","me");
$replace = array("SHE","ME","!!!");

$ret = str_replace($find, $replace, $str,$count);
var_dump($ret);
var_dump($count);

输出:

array
  0 => string "SHE told ME:"SHEllo world! but I don"t have any money!"" (length=55)
  1 => string "SHE is a hero not ME!" (length=21)

int 5

函数substr_replace()则用来在给定位置中查找和替换字符串中特定的子字符串。

它的原型如下所示:

string substr_replace(string string,string replacement,int start,int[length]);

这个函数使用字符串replacement替换字符串string中的一部分。具体是哪一部分则取决于起始位置值和可选参数length的值。start的值代表要替换字符串位置的开始偏移量。如果它为0或是一个正值,就是一个从字符串开始处计算的偏移量;如果它是一个负值,就是从字符串末尾开始的一个偏移量。

参数length是可选的,它代表PHP停止替换操作的位置。如果不给定它的值,它会从字符串start位置开始一直到字符串结束。如果length为零,替换字符串实际上会插入到字符串中而覆盖原有的字符串。一个正的length表示要用新字符串替换掉的字符串长度。一个负的length表示从字符串尾部开始到第length个字符停止替换。

例子:

<?php

    $replace = array("1234567","2: AAA","3: AAA");
    $rep = array("abcdef","2: BBB","3: CCC","llll");
    $ret = substr_replace($replace,$rep,1,2);
    var_dump($ret);

输出:

array
  0 => string "1abcdef4567" (length=11)
  1 => string "22: BBBAAA" (length=10)
  2 => string "33: CCCAAA" (length=10)
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。