PHP:正则函数:

本文详细介绍PHP中正则表达式的应用,包括字符串的匹配、查找、替换、分割与连接等操作,通过实例展示了preg_match、preg_match_all、preg_grep、preg_replace和preg_split函数的使用方法。

正则函数:
1.字符串的匹配与查找
preg_match();


preg_match匹配一次

<?php 

$str="linux and php and linux and java and html5";

$ptn='/linux/';
preg_match($ptn,$str,$arr);

echo '<pre>';
print_r($arr);
echo '</pre>';
 ?>

**

Array
(
    [0] => linux
)

preg_match_all();


preg_match_all逐行匹配

<?php 

$str="linux and php and linux and java and html5";

$ptn='/linux/';
preg_match_all($ptn,$str,$arr);

echo '<pre>';
print_r($arr);
echo '</pre>';
 ?>

**

Array
(
    [0] => Array
        (
            [0] => linux
            [1] => linux
        )

)

preg_grep();


preg_grep数组搜索

<?php 
$arr=array(
	'title1'=>'linux is very much!',
	'title2'=>'php is very much!',
	'title3'=>'java and pap is very much!',
	'title4'=>'html5 is and pxp very much!',
	'title5'=>'javascript and linux is very much!',
	'title6'=>'css3 and js and php and java is very much!'
);

$ptn='/p.p/';

$arr2=preg_grep($ptn,$arr);

echo '<pre>';
print_r($arr2);
echo '</pre>';
 ?>

**

Array
(
    [title2] => php is very much!
    [title3] => java and pap is very much!
    [title4] => html5 is and pxp very much!
    [title6] => css3 and js and php and java is very much!
)

2.字符串的替换
preg_replace();


**

<?php 
$str='linux and php and Linux';

$ptn='/linux/i';
$rep='LINUX';

echo preg_replace($ptn,$rep,$str);
 ?>

**

LINUX and php and LINUX

3.字符串的分割与连接
preg_split();


**

<?php 
$str='linux-and+php,and.Linux';

$ptn='/-|\+|,|\./';
$arr=preg_split($ptn,$str);

echo '<pre>';
print_r($arr);
echo '</pre>';
 ?>

**

Array
(
    [0] => linux
    [1] => and
    [2] => php
    [3] => and
    [4] => Linux
)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值