1. 程式人生 > 實用技巧 >PHP正則表示式核心技術完全詳解 第5節 php正則替換函式

PHP正則表示式核心技術完全詳解 第5節 php正則替換函式

作者:極客小俊 一個專注於web技術的80後
我不用拼過聰明人,我只需要拼過那些懶人 我就一定會超越大部分人!
CSDN@極客小俊,原創文章, B站技術分享
B站視訊 : Bilibili.com
個人部落格: cnblogs.com

PHP正則表示式核心技術完全詳解 第5節 php正則替換函式


說到替換呢 這裡我覺得首先要回憶一下字串的相關替換函式!

str_replace() 在字串中查詢字元,然後替換成想要的字元
str_ireplace() 在字串中查詢字元,然後替換成想要的字元 (不區分大小寫)
小提示 str_replace() 函式是全域性替換

練習: 在字串中查詢陣列對應的字元,設為紅色 程式碼如下:

//在字串中查詢陣列對應的字元,設為紅色

$string='[北京市朝陽區HTTP://www.baidu.com
    天安門北京市朝陽區http://www.sina.com天安門
    北京市朝陽區HTTP://www.163.com天安門]';

$data=[
    'http://www.baidu.com',
    'http://www.sina.com',
    'http://www.163.com'
];

//處理之前
echo nl2br($string);

echo '<hr>';

foreach ($data as $k=>$v){
    //這裡使用的是不區分大小寫的str_ireplace()方法來替換
    $string=str_ireplace($v, '<span style="color:red;">'.$v.'</span>', $string);
}

//處理之後
echo nl2br($string);


str_replace()方法中的引數 有三種使用技巧
第一種: str_replace(string,string,string,替換次數);
程式碼如下:

$string="online project php hosting user git includes php source-code php browser , 
php in-line editing wikis and ticketing free for public php open-source code!";
$search='php';
$replace='<span style="color:#ff0000;">php</span>';
echo str_replace($search, $replace, $string,$count);
echo '<br>';
echo '替換的次數是:'.$count.'次!';

第二種: str_replace(array,string,string,替換次數);
粗暴點 , 程式碼如下:

$string="online project 美國 php hosting 日本 user git includes php 韓國 source-code php browser , 
php in-line editing 法國 wikis and ticketing 澳大利亞 free for public php open-source code!";
//查詢的資料
$search=array(
    '美國',
    '日本',
    '韓國',
    '法國',
    '澳大利亞'
);
//替換為
$replace='<span style="color:#ff0000;">***</span>';

//開始替換
echo str_replace($search, $replace, $string,$count);
echo '<br>';
echo '替換的次數是:'.$count.'次!';

第三種: str_replace(array,array,string,替換次數);
程式碼如下:

$string="online project 美國 php hosting 日本 user git includes php 韓國 source-code php browser , 
php in-line editing 法國 wikis and ticketing 澳大利亞 free for public php open-source code!";

//查詢的資料
$search=array(
    '美國',
    '日本',
    '韓國',
    '法國',
    '澳大利亞'
);

//替換為
$replace=[
    '<span style="color:red;">***</span>',
    '<span style="color:blue;">???</span>',
    '<span style="color:yellow;">###</span>',
    '<span style="color:green;">@@@</span>',
    '<span style="color:#ccc;">&&&</span>',
];

//開始替換
echo str_replace($search, $replace, $string,$count);
echo '<br>';
echo '替換的次數是:'.$count.'次!';

以上就是回顧了一下 字串中的替換,別走開,接下來我們才要進入正則函式替換的正題哦!

PHP正則替換函式
preg_replace(); 正則中替換函式、返回值可能是一個字串也可能是一個數組

  1. 正常使用 preg_replace(引數..)
    引數列表:
    引數1: $pattern正則字串 或者 正則陣列
    引數2: $replacement替換為的字串 或者 字串陣列
    引數3: $string處理的字串 或者 字串陣列
    引數4: 每個模式在每個字串上進行替換幾次數,預設是 -1 全部替換
    引數5: 記錄替換次數的引用變數
    程式碼案例如下:
$string="online project php hosting  mysql user git includes php  source-code php browser 
php in-line editing  wikis and ticketing  free for public javascript open-source code!";
//查詢的資料
$search='/php | mysql | javascript/';
//替換為
$replace='<font color="red">***</font>';
//開始替換
echo preg_replace($search, $replace,$string);

  1. 使用子模式進行替換 子模式可以用到第二個引數當中
    程式碼案例如下:
$string="online project php hosting  mysql user git includes php  source-code php browser , 
php in-line editing  wikis and ticketing  free for public javascript open-source code!";
//查詢的資料
$search='/(php | mysql | javascript)/';
//替換為 這裡要記得字串的單雙引號對反向引用的作用哦! 前面提到過 !!不懂的同學可以回去看看!!
$replace="<font color='red'>\\1</font>";
//開始替換
echo preg_replace($search, $replace,$string);

  1. 在前兩個引數中都使用陣列,可以一起將多個模式(正則)同時替換對應的多個值
    替換UBB程式碼, 這裡就不介紹UBB是什麼了 自己百度一下就會知道簡單地一匹
    程式碼案例圖如下:
	$string="online [align=left][b]PHP開發[/b][/align] project [u]php[/u] hosting  mysql user git includes php  source-code php browser , 
php in-line [b]editing[/b]  wikis and ticketing  free for [font size=7]public[/font] javascript open-source code! A better way to work together
[align=center][color color=red]GitHub[/color][/align] brings teams [color color=blue]together[/color] to work through problems, move ideas forward, and learn from each other along the way.
[img width=100]http://localhost/test3/1.jpg[/img]";

//替換之前
echo $string;
echo '<hr>';

//查詢的資料
$pattern=array(
    '/\[u\](.+)\[\/u\]/',
    '/\[b\](.+)\[\/b\]/',
    '/\[align=(left|center|right)\](.+)\[\/align\]/',
    '/\[font(\s+)?(size=\d)?\](.+)\[\/font\]/',
    '/\[color(\s+)?color=([a-zA-Z]+)?\](.+?)\[\/color\]/',
    '/\[img\s(width=\d{1,3})?\](.+)\[\/img\]/'
);
//替換為
$replace=array(
    '<u>${1}</u>',
    '<b>${1}</b>',
    '<p align="${1}">${2}</p>',
    '<font ${2}>${3}</font>',
    '<span style="color:${2}">${3}</span>',
    '<img ${1} src="${2}"\>'
);

//開始替換
$result=preg_replace($pattern, $replace,$string);
echo $result;
echo '<hr>';

注意: 在php7以後preg_replace()函式第一個引數正則中已經不支援e這個模式修正符號、也就是不再支援/e修飾符,如果要使用函式就請用: preg_replace_callback()函式

preg_replace_callback(引數..)函式
作用: 執行一個正則表示式搜尋並且使用一個回撥進行替換,匹配到的字元和子組都包含在回撥函式的引數當中
引數列表:
引數1: 正則字串 或一個數組
引數2: 處理替換的回撥函式 支援 普通函式、匿名函式、類方法
引數3: 處理的字串
引數4: 每個模式在每個字串上進行替換幾次數,預設是 -1 全部替換
引數5: 記錄替換次數的引用變數
例1:匿名函式替換
程式碼案例如下

$string='Assign up to ten teammates to an issue or pull request to make
sure work has an owner. Mentioning other people or teams mysql
in the issue will notify them if php something changes. javascript
They can also stay in the php loop by opting to receive notifications whenever someone post';
$pattern='/mysql|php|javascript/';
echo preg_replace_callback($pattern, function($arr){
    //show($arr);
    echo $num++;
    return '<span style="color:red">'.strtolower($arr[0]).'</span>';
}, $string);

例2:類的方法替換方法
程式碼案例如下

$string='Assign up php to ten teammates to an issue or pull request to make
sure work has an owner. Mentioning other people or teams mysql
in the issue will notify them if php something changes. javascript
They can also stay in the php loop by opting to receive notifications whenever someone post';

$pattern=array(
    '/php/i',
    '/javascript/',
    '/mysql/'
);

class Replace{
    static public function txt($replace) {
        show($replace);
       if($replace[0]=='php'){
           return '<span style="color:red">'.$replace[0].'</span>';
       }
      return '<a href="" style="color:blue">'.$replace[0].'</a>';
    }
}

$result=preg_replace_callback($pattern, 'Replace::txt', $string);
echo $result;

"點贊" "評論" "收藏"

大家的支援就是我堅持下去的動力!

如果以上內容有任何錯誤或者不準確的地方,歡迎在下面