導航:首頁 > 編程語言 > phppregmatch函數

phppregmatch函數

發布時間:2025-08-08 19:01:46

『壹』 preg_match用法

preg_match 是 php 中用於正則表達式匹配的函數。它在 subject 字元串中搜索與 pattern 給出的正則表達式相匹配的內容。如果提供了 matches,則其會被搜索的結果所填充。$matches[0] 將包含與整個模式匹配的文本,$matches[1] 將包含與第一個捕獲的括弧中的子模式所匹配的文本,以此類推。

flags 參數可以包含以下標記:PREG_OFFSET_CAPTURE,如果設定本標記,對每個出現的匹配結果也同時返回其附屬的字元串偏移量。注意這改變了返回的數組的值,使其中的每個單元也是一個數組,其中第一項為匹配字元串,第二項為其偏移量。本標記自 PHP 4.3.0 起可用。

如果出錯,preg_match() 返回 FALSE。preg_match() 返回 pattern 所匹配的次數。要麼是 0 次(沒有匹配)或 1 次,因為 preg_match() 在第一次匹配之後將停止搜索。而 preg_match_all() 則會一直搜索到 subject 的結尾處。

例如,要在文本中搜索「php」,可以使用以下代碼:

<?php

// 模式定界符後面的 "i" 表示不區分大小寫字母的搜索

if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {

print "A match was found.";}

else {print "A match was not found.";}

?>

如果只想查看一個字元串是否包含在另一個字元串中,不要用 preg_match()。可以用 strpos() 或 strstr() 替代,因為它們更快。

另一個例子,要搜索單詞「web」,可以使用以下代碼:

<?php

/* 模式中的 \b 表示單詞的邊界,因此只有獨立的 "web" 單詞會被匹配,

* 而不會匹配例如 "webbing" 或 "cobweb" 中的一部分 */

if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of choice.")) {

print "A match was found.";}

else {print "A match was not found.";}

if (preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.")) {

print "A match was found.";}

else {print "A match was not found.";}

?>

另一個例子,從 URL 中取出域名,可以使用以下代碼:

<?php

// 從 URL 中取得主機名

preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.php.net/index.html", $matches);

$host = $matches[2]; // 從主機名中取得後面兩段

preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);

echo "domain name is: {$matches[0]}\n";

?>

『貳』 php中的preg_match()函數

preg_match()函數用於正則表達式知識匹配,如果成功則返回1,否則返回0。

Preg_match()在成功匹配之後停止匹配,如果要實現所有結果的內部匹配,則使用preg_match_all()函數。

php函數取得字元串長度:

1.首先,創建一個新的PHP文件並將其命名為test.php。

閱讀全文

與phppregmatch函數相關的資料

熱點內容
打板交易系統源碼 瀏覽:622
菲律賓伺服器地址大全 瀏覽:59
安卓系統如何播放愛奇藝視頻 瀏覽:144
設計評分演算法 瀏覽:888
我的世界為什麼進伺服器不動 瀏覽:128
伺服器怎麼搞資料庫 瀏覽:100
大象影視app閃退是什麼問題 瀏覽:380
政府辦文件夾 瀏覽:212
圖片如何做成pdf 瀏覽:367
深圳南山的程序員 瀏覽:364
雲的伺服器的租賃費用 瀏覽:355
怎樣學編程進步高 瀏覽:323
生成驗證碼的java代碼 瀏覽:899
linuxhttp文件伺服器 瀏覽:854
安卓用什麼軟體跑電快 瀏覽:743
python人員一月工資多少 瀏覽:162
pdfcopy 瀏覽:333
華為清空介面配置命令 瀏覽:299
pdf編進 瀏覽:751
javahttpconnection 瀏覽:920