加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式函数与字符串处理函数

发布时间:2020-12-14 06:46:11 所属栏目:百科 来源:网络整理
导读:1.字符串匹配与查找 a.如果可以使用字符串处理函数处理的,不要使用正则表达式(功能强,效率低) b.使用正则表达式匹配函数: (1)preg_match:匹配用户名/email/url ?php if(isset($_POST['dosubmit'])){ if(!preg_match('/^S+$/',$_POST['username'])){

1.字符串匹配与查找

a.如果可以使用字符串处理函数处理的,不要使用正则表达式(功能强,效率低)
b.使用正则表达式匹配函数:

(1)preg_match:匹配用户名/email/url
<?php    
    if(isset($_POST['dosubmit'])){
        if(!preg_match('/^S+$/',$_POST['username'])){
            echo "用户名不能为空<br>";
        }
        if(!preg_match('/w+([+-.]w+)*@w+([-.]w+)*.w+([-.]w+)*/i',$_POST['email'])){
            echo "不是正确的email格式<br>";
        }
        if(!preg_match('/(https?|fps?)://(www|mail|bbs|fps).(.*?).(net|com|org|cn)([w+./=?&;%]*)?/',$_POST['url'],$arr)){
            echo "不是正确的url格式<br>";
        }else{
            echo "<pre>";
            print_r($arr);
            echo "</pre>";
            /*
             Array
            (
                [0] => https://www.baidu.com/
                [1] => https
                [2] => www
                [3] => baidu
                [4] => com
                [5] => /
            )*/             
        }
    }
?>
<!DOCTYPE html>
<html>
    <head>
        
    </head>
    <body>
        <form action="namespace.php" method="post">
            <label for="username">name:</label><input type="text" id="username" name="username"/>
            <label for="email">email:</label><input type="text" id="email" name="email"/>
            <label for="url">url:</label><input type="text" id="url" name="url"/>
            <button type="submit" name="dosubmit">提交</button>
        </form>
    </body>
</html>
(2)preg_match_all:以匹配url为例展示,可以匹配全部url,返回多维数组(视子模式而定),可以传入第四个参数,以改变多维数组的构成模式
<?php
    $str='驾考难度大升级 保险公司抢食http://www.liuxue86.com/a/3101593.html千亿市场蛋糕,根据公安部、交通运输部《机动车驾驶培训教https://www.segmentfault.com/write?draftId=1220000010640798学与考试大纲》要求,调整相关考试内容:科目一涉及安全文明';
    if(!preg_match_all('/(https?|fps?)://(www|mail|bbs|fps).(.*?).(net|com|org|cn)([w+./=?&;%]*)?/',$str,$arr)){
        echo "不是正确的url格式<br>";
    }else{
        echo "<pre>";
        print_r($arr);
        echo "</pre>";    
        /*
        Array
        (
            [0] => Array
                (
                    [0] => http://www.liuxue86.com/a/3101593.html
                    [1] => https://www.segmentfault.com/write?draftId=1220000010640798
                )
        
            [1] => Array
                (
                    [0] => http
                    [1] => https
                )
        
            [2] => Array
                (
                    [0] => www
                    [1] => www
                )
        
            [3] => Array
                (
                    [0] => liuxue86
                    [1] => segmentfault
                )
        
            [4] => Array
                (
                    [0] => com
                    [1] => com
                )
        
            [5] => Array
                (
                    [0] => /a/3101593.html
                    [1] => /write?draftId=1220000010640798
                )
        )*/
    }
?>
(3)preg_grep:对多个字符串的数组进行匹配,如下:
<?php
    $arr=array('aaaaaa','2222222222','bbbbbbb','2222222222');
    $result=preg_grep('/d/',$arr);
    print_r($result);
    //Array ( [1] => 2222222222 [3] => 2222222222 )
?>
c.使用字符串匹配函数:strstr/strpos/substr
function getFileName($url){
        $str=strrpos($url,'/')+1;
        return substr($url,$str);
    }
    echo getFileName("https://segmentfault.com/write?draftId=1220000010640798/aaa.php");

2.字符串的分割与连接

a.使用字符串函数:explode/implode/join
b.使用正则函数:preg_split ( $pattern,$subject [,$limit = -1 [,$flags = 0 ]] ),其中limit为分割的总个数(即数组长度),-1表示不限制个数,flags为可选系统参数

注:字符偏移量为该字符相对于首字符的位置

<?php
    $str='aaaaaa,bbbbb.
    ccccccc';
    $arr=preg_split('/[.,]/',2);
    print_r($arr);
    //Array ( [0] => aaaaaa [1] => bbbbb. ccccccc )
?>

3.字符串的替换

a.字符串函数:str_replace ( mixed $search,mixed $replace,mixed $subject [,int &$count ] ),&$count返回替换次数,由于混合类型,因此可以以数组替换数组,如下:

<?php
    $str='汇集全网优质网址及资源的中文上网导航。及时收录影视、音乐、小说、游戏等分类的网址和内容,让您的网络生活更简单精彩。';
    $result=str_replace(array('资源','收录'),array('hhhh','uuuuu'),$count);
    echo $result.'<br>';
    echo $count;
?>

b.正则函数:mixed preg_replace ( mixed $pattern,mixed $replacement,int $limit = -1 [,int &$count ]] )

*注1*:&$count不同于字符串函数,为主动传值,指示替换次数
<?php
    $str='汇集全网优质<b>网</b>址及资<p>源</p>的中文上网导航。及时收录影视、音乐、小说、游戏等分类的网址和内容,让您的网络生活更简单精彩。';
    $result=preg_replace('/&;[/!]*?[^&;&;]*?&;/is','',1);//替换HTML标签,只替换了一次
    echo $result.'<br>';    
?>
*注2*:替换项$replacement可以使用12等借用正则中子模式的内容,如下:
<?php
    $str='汇集全网优质网址http://www.baidu.com及资源的https://www.segmentfault.com/write?freshman=1中文上网导航。';
    $result=preg_replace('/(https?|fps?)://(www|mail|bbs|fps).(.*?).(net|com|org|cn)([w+./=?&;%]*)?/','<a href=""></a>',$str);
    echo $result.'<br>';    
?>
*注3*:该函数也可以处理三个参数全是数组的情况,如下:
<?php
    $str=array('汇集全网1优质<b>网</b>址http://www.baidu.com及资2源的https://www.segmentfault.com/write?freshman=1中文<p>上</p>网33导航。','汇集全网1优质<b>网</b>址http://www.baidu.com及资2源的https://www.segmentfault.com/write?freshman=1中文<p>上</p>网33导航。','汇集全网1优质<b>网</b>址http://www.baidu.com及资2源的https://www.segmentfault.com/write?freshman=1中文<p>上</p>网33导航。');
    //要注意替换顺序,如果先将网址替换为a标签,再去除所有HTML标签,会将链接也去除
    $arr=array('/(https?|fps?)://(www|mail|bbs|fps).(.*?).(net|com|org|cn)([w+./=?&;%]*)?/','/&;[/!]*?[^&;&;]*?&;/is','/d/');
    $replacement=array('<a href=""></a>',' ','@');
    $result=preg_replace($arr,$replacement,$str);
    echo "<pre>";
    print_r($result).'<br>';    
    echo "</pre>";
?>

4.其他正则PCRE函数

a.preg_replace_callback:带回调函数

mixed preg_replace_callback ( mixed $pattern,callable $callback,int &$count ]] )
$str='汇集全网2014优质1网2址3导2015航。';
    function num($num){//传入参数为匹配到的子模式数组
        return $num[1]+1;
    }
    $result=preg_replace_callback('/(d{4})/',"num",$str);
    echo $result;

b.preg_quote:将正则语法中应该转义的符号加上转义符

string preg_quote ( string $str [,string $delimiter = NULL ] )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读