php 字符串替换函数学习
两个php字符串替换函数,一个是str_ireplace()一个是substr_replace()这两个函数都比较好用。
字符串替换技术可以通过函数实现:
str_ireplace()函数和substr_replace()函数
str_ireplace()函数
使用新的子字符串替换原始字符串中被指定要替换的字符串,语法:
mixed str_ireplace(mixed search,mixed replace,mixed subject[,int&count])
参数search:必要参数,指定需要查找的字符串。
参数replace:必要参数,指定替换的值。
参数subject:必要参数,指定查找的范围。
参数count:可选参数,(带中括号的为可选参数),获取执行替换的数量。
例子:
$str2=”某某”;
$str1=”**”;
$str=”某某网站的地址是www.phpfensi.com ,某某网站主要记录一些学习php的笔记和感想以及各种软件知识”;
echo str_ireplace($str2,$str1,$str); //str2查找的值,str1替换的值,str范围
?>
在本例中,将演示带有数组和count变量的 str_ireplace()函数:
$arr = array("blue","red","green","yellow");
print_r(str_ireplace("red","pink",$arr,$i));
echo "Replacements: $i";
?>
//输出:
Array
(
[0] => blue
[1] => pink
[2] => green
[3] => yellow
)
Replacements:1
例子3
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_ireplace($find,$replace,$arr));
?> //脚本学堂 www.jbxue.com
//输出:
Array
(
[0] => B
[1] =>
[2] => !
)
substr_replace()函数
对指定字符串中的部分字符串进行替换,语法:
string substr_replace(string str,string repl,int start,[int length])
参数str:指定要操作的原始字符串。
参数repl:必要参数,指定替换后的新字符串。
参数start:指定替换字符串开始的位置。
参数length:指定返回的字符串长度。
例4:
substr_replace('eggs','x',-1,-1); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
?> Same as:
<?php
substr_replace('eggs','x',-1,0); //eggxs
?>
<?php
substr_replace('huevos','x',-2,-2); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
?> Same as:
<?php
substr
_replace('huevos','x',-2,0); //huevxos
?>
您可能感兴趣的文章:
php 字符串替换函数学习
python怎么替换字符串的内容
php替换html内容的小函数
php查找字符串中http地址
php 字符串替换函数
php表单提交特殊字符过滤方法
mysql replace的用法(替换指定字段字符串)
正则表达式处理函数 preg_match,preg_match_all
php substr_replace函数怎么用
php回车与空格字符替换函数