在PHP中给我们提供两套正则表达式函数,POSIX 扩展正则表达式函数(ereg_)和Perl 兼容正则表达式函数(preg_),这两个函数功能一样,Perl 兼容正则表达式函数库效率高, 这里和这符串处理函数对比介绍,能使用字符串处理函数完成的功能,就不要使用正则表达式处理函数
2.字符串替换
b. str_replace(array, string, string)
c. str_replace(array, array, string)
preg_replace() 正则中替换函数
1. 正常使用 preg_replace('string', 'string', 'stirng');
2. 在正则中的子模式,可以用到二个参数中
3. 在第二个参数中调用函数, 需要在模式中使用 e 模式修正符号
4. 就是在前两个参数中都使用数组, 可以一起将多个模式(正则)同时替换成多个值的形式
3、字符串分割
explode
preg_split
1. 字符串的匹配与查找
字符串处理函数
strstr(a,b)
返回a 字符串从b 第一次出现的位置开始到a 结尾的字符串。
<span style="font-size:18px;">$a='visit';
$b='US President Barack Obama is in Cuba from March 20 to 22 for a historic visit to the island, reported China Daily.';
$c=strstr($b,$a);
echo $c; //visit to the island, reported China Daily.</span>
strpos(a,b)
返回a 字符串从b 第一次出现的位置开始到a 结尾的位置,不存在返回false
<span style="font-size:18px;">$a='visit';
$b='Cuba visit part of Obama’s legacy.';
$c=strpos($b,$a);
if ($c!==false){
echo "在'$b'中存在'$a'";
}else{
echo "在'$b'中不存在'$a'";
}
</span>
preg_match(a,b,c)
执行一个正则表达式匹配
以正则a验证字符串b,c是搜素结果
<span style="font-size:18px;">$pattern="/\Bis\b/"; //正则表达式模式
$string="this is a island"; //需要匹配的字符串
if (preg_match($pattern,$string)){
echo '匹配成功!';
}else{
echo '匹配失败!';
} //匹配成功</span>
2.字符串替换
str_replace(a,b,c)
在c中用b替换a
str_ireplace() 不区分大小写
a. str_replace(string, string, string)<span style="font-size:18px;"><?php
header("Content-Type: text/html; charset=UTF-8");
$a='No pains, no gains.';
$b='yes';
echo (str_ireplace('no',$b,$a));//yes pains, yes gains.</span>
b. str_replace(array, string, string)
可以用于屏蔽非法关键字
<span style="font-size:18px;"><?php
header("Content-Type: text/html; charset=UTF-8");
$a='Keep good men company and you shall beof the number.';
$b=array('men','you','the');
$c='**';
echo (str_ireplace($b,$c,$a)); //Keep good ** company and ** shall beof ** number.</span>
c. str_replace(array, array, string)
批量替换
<span style="font-size:18px;"><?php
header("Content-Type: text/html; charset=UTF-8");
$a='Keep good men company and you shall beof the number.';
$b=array('men','you','the');
$c=array('MEN','YOU','THE');
echo (str_ireplace($b,$c,$a));//Keep good MEN company and YOU shall beof THE number.</span>
preg_replace() 正则中替换函数
1. 正常使用 preg_replace('string', 'string', 'stirng');
2. 在正则中的子模式,可以用到二个参数中
3. 在第二个参数中调用函数, 需要在模式中使用 e 模式修正符号
4. 就是在前两个参数中都使用数组, 可以一起将多个模式(正则)同时替换成多个值的形式
3、字符串分割
explode
按某个字符或字符串去分割
<span style="font-size:18px;"><?php
header("Content-Type: text/html; charset=UTF-8");
$a='Keep good men company and you shall beof the number.';
print_r (explode(' ',$a)); //Array( [0] => Keep [1] => good [2] => men [3] => company [4] => and [5] => you [6] => shall [7] => beof [8] => the [9] => number.)</span>
preg_split
按一个正则的模式去分割
<span style="font-size:18px;"><?php
header("Content-Type: text/html; charset=UTF-8");
$a='A faithful friend is hard to find.';
//print_r (explode(' ',$a));
print_r(preg_split('/[\s]+/',$a));//Array( [0] => A [1] => faithful [2] => friend [3] => is [4] => hard [5] => to [6] => find.)</span>