PHPRegex匹配字串中的指定標籤

來源:互聯網
上載者:User

在 PHP 應用中,Regex主要用於:

•正則匹配:根據Regex匹配相應的內容
•正則替換:根據Regex匹配內容並替換
•正則分割:根據Regex分割字串

常用

preg_match_all()
preg_match_all() 函數用於進行Regex全域匹配,成功返回整個模式比對的次數(可能為零),如果出錯返回 FALSE 。

文法:

int preg_match_all( string pattern, string subject, array matches [, int flags ] )


執行個體

$str = "之二寬闊的甘家口東#標籤1#標籤2 #標籤3。#標籤4,都發$1234 ¥xc,cvm , ¥12,dflksjf如何#標籤5.x

 代碼如下 複製代碼
#tag6.cvxcv“";
preg_match_all('/#([a-zA-Z0-9x7f-xff]+)/', $str, $mat);
print_r($mat);
 
preg_match("/[x{00a5}x{ffe5}](d+)/u", $str, $mat);
print_r($mat);

正則匹配中文漢字根據頁面編碼不同而略有區別:

•GBK/GB2312編碼:[x80-xff>]+ 或 [xa1-xff]+
•UTF-8編碼:[x{4e00}-x{9fa5}]+/u
例子:

 代碼如下 複製代碼

<?php
$str = "學習php是一件快樂的事。";
preg_match_all("/[x80-xff]+/", $str, $match);
//UTF-8 使用:
//preg_match_all("/[x{4e00}-x{9fa5}]+/u", $str, $match);
print_r($match);
?>

補充說明:

雙位元組字元編碼範圍

1. GBK (GB2312/GB18030)
x00-xff GBK雙位元組編碼範圍
x20-x7f ASCII
xa1-xff 中文 gb2312
x80-xff 中文 gbk

2. UTF-8 (Unicode)

u4e00-u9fa5 (中文)
x3130-x318F (韓文
xAC00-xD7A3 (韓文)
u0800-u4e00 (日文)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.