php的正則處理函數(shù)總結(jié)分析
Jun 13, 2016 pm 12:28 PM
preg_grep
(PHP?4,?PHP?5)
preg_grep?--???返回與模式匹配的數(shù)組單元?
說明
array?preg_grep?(?string?pattern,?array?input?[,?int?flags]?)
preg_grep()?返回一個(gè)數(shù)組,其中包括了?input?數(shù)組中與給定的?pattern?模式相匹配的單元。?
flags?可以是以下標(biāo)記:?
PREG_GREP_INVERT?
如果傳遞入此標(biāo)記,preg_grep()?會(huì)返回輸入數(shù)組中不匹配給定?pattern?的單元。本標(biāo)記自?PHP?4.2.0?起可用。?
自?PHP?4.0.4?起,preg_grep()?返回的結(jié)果使用從輸入數(shù)組來的鍵名進(jìn)行索引。如果不希望這樣的結(jié)果,用?array_values()?對?preg_grep()?返回的結(jié)果重新索引。?
上面是手冊上對preg_grep()的說明。首先這是perl兼容的正則函數(shù),所以我猜想preg_grep的意思是p(perl)reg(regular)_grep,其特點(diǎn)是可做用于數(shù)組,通過自己擴(kuò)展,可用做多維數(shù)組中的正則匹配,并且可以通過flags參數(shù)返回匹配或者非匹配數(shù)組。其效率比用foreach(...){if...}結(jié)構(gòu)快很多(未驗(yàn)證),而且可匹配復(fù)雜模式。在搜索、分檢等應(yīng)用中用途不小。
例:
$arr?=?array('abc'=>12.213,'bb'=>12345,'ba'=>23.2321,34.3,'23'=>'3.3','23434'=>'bbb');
//?返回所有含有浮點(diǎn)數(shù)的數(shù)組元素。
$fl_array?=?preg_grep?("/^(\d+)?\.\d+$/",?$arr);
print_r($fl_array);
?>
preg_match
(PHP?3?>=?3.0.9,?PHP?4,?PHP?5)
preg_match?--?進(jìn)行正則表達(dá)式匹配
說明
int?preg_match?(?string?pattern,?string?subject?[,?array?matches?[,?int?flags]]?)
在?subject?字符串中搜索與?pattern?給出的正則表達(dá)式相匹配的內(nèi)容。?
如果提供了?matches,則其會(huì)被搜索的結(jié)果所填充。$matches[0]?將包含與整個(gè)模式匹配的文本,$matches[1]?將包含與第一個(gè)捕獲的括號中的子模式所匹配的文本,以此類推。?
flags?可以是下列標(biāo)記:?
PREG_OFFSET_CAPTURE?
如果設(shè)定本標(biāo)記,對每個(gè)出現(xiàn)的匹配結(jié)果也同時(shí)返回其附屬的字符串偏移量。注意這改變了返回的數(shù)組的值,使其中的每個(gè)單元也是一個(gè)數(shù)組,其中第一項(xiàng)為匹配字符串,第二項(xiàng)為其偏移量。本標(biāo)記自?PHP?4.3.0?起可用。?
flags?參數(shù)自?PHP?4.3.0?起可用。?
preg_match()?返回?pattern?所匹配的次數(shù)。要么是?0?次(沒有匹配)或?1?次,因?yàn)?preg_match()?在第一次匹配之后將停止搜索。preg_match_all()?則相反,會(huì)一直搜索到?subject?的結(jié)尾處。如果出錯(cuò)?preg_match()?返回?FALSE。?
提示:?如果只想查看一個(gè)字符串是否包含在另一個(gè)字符串中,不要用?preg_match()。可以用?strpos()?或?strstr()?替代,要快得多。?
上面是手冊里對preg_match()的說明,我認(rèn)為這個(gè)函數(shù)的功用在于他可做來做驗(yàn)證,也就是某字符串是否符合某特定要求。其局限是上面所說的要么匹配0次,要么1次。并且返回值是匹配次數(shù)。當(dāng)需要全匹配時(shí)可使用preg_match_all().另外值得一提的是$matches數(shù)組的作用,可做自模式的返回值,有時(shí)很有用。
例:
if?(preg_match?("/(\bweb\b)\s(\d)/i",?"PHP?is?the?web?45?scripting?web?34?language?of?choice.",$match))?{
?????print?"A?match?was?found.";
print_r($match);
}?else?{
?????print?"A?match?was?not?found.";
}
?>
//?從?URL?中取得主機(jī)名
preg_match("/^(http:\/\/)?([^\/]+)/i",
?????"http://www.php.net/index.html",?$matches);
$host?=?$matches[2];
//?從主機(jī)名中取得后面兩段
preg_match("/[^\.\/]+\.[^\.\/]+$/",?$host,?$matches);
echo?"domain?name?is:?{$matches[0]}\n";
?>?
preg_match_all
(PHP?3?>=?3.0.9,?PHP?4,?PHP?5)
preg_match_all?--?進(jìn)行全局正則表達(dá)式匹配
手冊上該函數(shù)的解釋非常明確,就不多做說明了。
說明
int?preg_match_all?(?string?pattern,?string?subject,?array?matches?[,?int?flags]?)
在?subject?中搜索所有與?pattern?給出的正則表達(dá)式匹配的內(nèi)容并將結(jié)果以?flags?指定的順序放到?matches?中。?
搜索到第一個(gè)匹配項(xiàng)之后,接下來的搜索從上一個(gè)匹配項(xiàng)末尾開始。?
flags?可以是下列標(biāo)記的組合(注意把?PREG_PATTERN_ORDER?和?PREG_SET_ORDER?合起來用沒有意義):?
PREG_PATTERN_ORDER?
對結(jié)果排序使?$matches[0]?為全部模式匹配的數(shù)組,$matches[1]?為第一個(gè)括號中的子模式所匹配的字符串組成的數(shù)組,以此類推。?
preg_match_all?("|]+>(.*)[^>]+>|U",
?????"example:?
?????$out,?PREG_PATTERN_ORDER);
print?$out[0][0].",?".$out[0][1]."\n";
print?$out[1][0].",?".$out[1][1]."\n";
?>??
本例將輸出:?
example:?,?
example:?,?this?is?a?test
因此,$out[0]?包含匹配整個(gè)模式的字符串,$out[1]?包含一對?HTML?標(biāo)記之間的字符串。?
PREG_SET_ORDER?
對結(jié)果排序使?$matches[0]?為第一組匹配項(xiàng)的數(shù)組,$matches[1]?為第二組匹配項(xiàng)的數(shù)組,以此類推。?
preg_match_all?("|]+>(.*)[^>]+>|U",
?????"example:?
?????$out,?PREG_SET_ORDER);
print?$out[0][0].",?".$out[0][1]."\n";
print?$out[1][0].",?".$out[1][1]."\n";
?>??
本例將輸出:?
example:?,?example:
本例中,$matches[0]?是第一組匹配結(jié)果,$matches[0][0]?包含匹配整個(gè)模式的文本,$matches[0][1]?包含匹配第一個(gè)子模式的文本,以此類推。同樣,$matches[1]?是第二組匹配結(jié)果,等等。?
PREG_OFFSET_CAPTURE?
如果設(shè)定本標(biāo)記,對每個(gè)出現(xiàn)的匹配結(jié)果也同時(shí)返回其附屬的字符串偏移量。注意這改變了返回的數(shù)組的值,使其中的每個(gè)單元也是一個(gè)數(shù)組,其中第一項(xiàng)為匹配字符串,第二項(xiàng)為其在?subject?中的偏移量。本標(biāo)記自?PHP?4.3.0?起可用。?
如果沒有給出標(biāo)記,則假定為?PREG_PATTERN_ORDER。?
返回整個(gè)模式匹配的次數(shù)(可能為零),如果出錯(cuò)返回?FALSE。?
例子?1.?從某文本中取得所有的電話號碼
preg_match_all?("/\(????(\d{3})????\)????(?(1)???[\-\s]?)?\d{3}-\d{4}/x",
?????????????????"Call?555-1212?or?1-800-555-1212",?$phones);
?>??
例子?2.?搜索匹配的?HTML?標(biāo)記(greedy)
//?\\2?是一個(gè)逆向引用的例子,其在?PCRE?中的含義是
//?必須匹配正則表達(dá)式本身中第二組括號內(nèi)的內(nèi)容,本例中
//?就是?([\w]+)。因?yàn)樽址陔p引號中,所以需要
//?多加一個(gè)反斜線。
$html?=?"bold?textclick?me";
preg_match_all?("/(]*>)(.*)()/",?$html,?$matches);
for?($i=0;?$i???echo?"matched:?".$matches[0][$i]."\n";
???echo?"part?1:?".$matches[1][$i]."\n";
???echo?"part?2:?".$matches[3][$i]."\n";
???echo?"part?3:?".$matches[4][$i]."\n\n";
}
?>??
preg_quote
(PHP?3?>=?3.0.9,?PHP?4,?PHP?5)
preg_quote?--?轉(zhuǎn)義正則表達(dá)式字符
說明
string?preg_quote?(?string?str?[,?string?delimiter]?)
preg_quote()?以?str?為參數(shù)并給其中每個(gè)屬于正則表達(dá)式語法的字符前面加上一個(gè)反斜線。如果你需要以動(dòng)態(tài)生成的字符串作為模式去匹配則可以用此函數(shù)轉(zhuǎn)義其中可能包含的特殊字符。?
如果提供了可選參數(shù)?delimiter,該字符也將被轉(zhuǎn)義??梢杂脕磙D(zhuǎn)義?PCRE?函數(shù)所需要的定界符,最常用的定界符是斜線?/。?
正則表達(dá)式的特殊字符包括:.?\?+?*???[?^?]?$?(?)?{?}?=?!??|?:。?
注:?本函數(shù)可安全用于二進(jìn)制對象。
上面是手冊上的解釋,也很明白,不多說了,另外手冊上還有一注釋就是該函數(shù)可安全用于二進(jìn)制對象,這點(diǎn)很有用。
例:?例子?1.?preg_quote()?例子
$keywords?=?'$40?for?a?g3/400';
$keywords?=?preg_quote($keywords,?'/');
echo?$keywords;?//?returns?\$40?for?a?g3\/400
?>??
例子?2.?給某文本中的一個(gè)單詞加上斜體標(biāo)記
//?本例中,preg_quote($word)?用來使星號不在正則表達(dá)式中
//?具有特殊含義。
$textbody?=?"This?book?is?*very*?difficult?to?find.";
$word?=?"*very*";
$textbody?=?preg_replace?("/".preg_quote($word)."/",
???????????????????????????"".$word."",
???????????????????????????$textbody);
?>??
接下來就是應(yīng)用超靈活、、功能超強(qiáng)大、使用超廣泛的preg_replace函數(shù)。
preg_replace
(PHP?3?>=?3.0.9,?PHP?4,?PHP?5)
preg_replace?--?執(zhí)行正則表達(dá)式的搜索和替換
說明
mixed?preg_replace?(?mixed?pattern,?mixed?replacement,?mixed?subject?[,?int?limit]?)
在?subject?中搜索?pattern?模式的匹配項(xiàng)并替換為?replacement。如果指定了?limit,則僅替換?limit?個(gè)匹配,如果省略?limit?或者其值為?-1,則所有的匹配項(xiàng)都會(huì)被替換。?
replacement?可以包含?\\n?形式或(自?PHP?4.0.4?起)$n?形式的逆向引用,首選使用后者。每個(gè)此種引用將被替換為與第?n?個(gè)被捕獲的括號內(nèi)的子模式所匹配的文本。n?可以從?0?到?99,其中?\\0?或?$0?指的是被整個(gè)模式所匹配的文本。對左圓括號從左到右計(jì)數(shù)(從?1?開始)以取得子模式的數(shù)目。?
對替換模式在一個(gè)逆向引用后面緊接著一個(gè)數(shù)字時(shí)(即:緊接在一個(gè)匹配的模式后面的數(shù)字),不能使用熟悉的?\\1?符號來表示逆向引用。舉例說?\\11,將會(huì)使?preg_replace()?搞不清楚是想要一個(gè)?\\1?的逆向引用后面跟著一個(gè)數(shù)字?1?還是一個(gè)?\\11?的逆向引用。本例中的解決方法是使用?\${1}1。這會(huì)形成一個(gè)隔離的?$1?逆向引用,而使另一個(gè)?1?只是單純的文字。?
如果搜索到匹配項(xiàng),則會(huì)返回被替換后的?subject,否則返回原來不變的?subject。?
preg_replace()?的每個(gè)參數(shù)(除了?limit)都可以是一個(gè)數(shù)組。如果?pattern?和?replacement?都是數(shù)組,將以其鍵名在數(shù)組中出現(xiàn)的順序來進(jìn)行處理。這不一定和索引的數(shù)字順序相同。如果使用索引來標(biāo)識哪個(gè)?pattern?將被哪個(gè)?replacement?來替換,應(yīng)該在調(diào)用?preg_replace()?之前用?ksort()?對數(shù)組進(jìn)行排序。?
如果?subject?是個(gè)數(shù)組,則會(huì)對?subject?中的每個(gè)項(xiàng)目執(zhí)行搜索和替換,并返回一個(gè)數(shù)組。?
如果?pattern?和?replacement?都是數(shù)組,則?preg_replace()?會(huì)依次從中分別取出值來對?subject?進(jìn)行搜索和替換。如果?replacement?中的值比?pattern?中的少,則用空字符串作為余下的替換值。如果?pattern?是數(shù)組而?replacement?是字符串,則對?pattern?中的每個(gè)值都用此字符串作為替換值。反過來則沒有意義了。?
/e?修正符使?preg_replace()?將?replacement?參數(shù)當(dāng)作?PHP?代碼(在適當(dāng)?shù)哪嫦蛞锰鎿Q完之后)。提示:要確保?replacement?構(gòu)成一個(gè)合法的?PHP?代碼字符串,否則?PHP?會(huì)在報(bào)告在包含?preg_replace()?的行中出現(xiàn)語法解析錯(cuò)誤。?
注:?limit?參數(shù)是?PHP?4.0.1pl2?之后加入的。?
我認(rèn)為其強(qiáng)大之處就是他不但可以處理字符串,而且可以處理數(shù)組,并且他的逆向引用功能非常靈活。基本上他可以滿足普通用戶的大部分需求,如果他不能勝任,那么我們還有preg_replace_callback()函數(shù),可以自定義回調(diào)函數(shù),滿足你的高級要求。如設(shè)計(jì)過濾器等。
preg_replace_callback
(PHP?4?>=?4.0.5,?PHP?5)
preg_replace_callback?--?用回調(diào)函數(shù)執(zhí)行正則表達(dá)式的搜索和替換
說明
mixed?preg_replace_callback?(?mixed?pattern,?callback?callback,?mixed?subject?[,?int?limit]?)
本函數(shù)的行為幾乎和?preg_replace()?一樣,除了不是提供一個(gè)?replacement?參數(shù),而是指定一個(gè)?callback?函數(shù)。該函數(shù)將以目標(biāo)字符串中的匹配數(shù)組作為輸入?yún)?shù),并返回用于替換的字符串。?
例子?1.?preg_replace_callback()?例子
???//?此文本是用于?2002?年的,
???//?現(xiàn)在想使其能用于?2003?年
???$text?=?"April?fools?day?is?04/01/2002\n";
???$text.=?"Last?christmas?was?12/24/2001\n";
???//?回調(diào)函數(shù)
???function?next_year($matches)?{
?????//?通常:$matches[0]?是完整的匹配項(xiàng)
?????//?$matches[1]?是第一個(gè)括號中的子模式的匹配項(xiàng)
?????//?以此類推
?????return?$matches[1].($matches[2]+1);
???}
???echo?preg_replace_callback(
???????????????"|(\d{2}/\d{2}/)(\d{4})|",
???????????????"next_year",
???????????????$text);
???//?結(jié)果為:
???//?April?fools?day?is?04/01/2003
???//?Last?christmas?was?12/24/2002
?>??
You'll?often?need?the?callback?function?for?a?preg_replace_callback()?in?just?one?place.?In?this?case?you?can?use?create_function()?to?declare?an?anonymous?function?as?callback?within?the?call?to?preg_replace_callback().?By?doing?it?this?way?you?have?all?information?for?the?call?in?one?place?and?do?not?clutter?the?function?namespace?with?a?callback?functions?name?not?used?anywhere?else.?
對于使用preg_replace_callback()函數(shù)的朋友來說,你應(yīng)該回需要callback函數(shù)(否則用他干嘛,直接用preg_replace不是更好),不過也經(jīng)常只是用一處。既然這樣你可以用create_function()來聲明一個(gè)匿名函數(shù)作為preg_replace_callback()的回調(diào)函數(shù)。這樣,我們即滿足了聲明信息的需要,有不致因這個(gè)不會(huì)再用到的函數(shù)名而混亂。
例子?2.?preg_replace_callback()?和?create_function()
???/*?一個(gè)?UNIX?風(fēng)格的命令行過濾器,將每個(gè)段落開頭的
???*?大寫字母轉(zhuǎn)換成小寫字母?*/
???$fp?=?fopen("php://stdin",?"r")?or?die("can't?read?stdin");
???while?(!feof($fp))?{
???????$line?=?fgets($fp);
???????$line?=?preg_replace_callback(
???????????'|
\s*\w|',
???????????create_function(
???????????????//?這里使用單引號很關(guān)鍵,
???????????????//?否則就把所有的?$?換成?\$
???????????????'$matches',
???????????????'return?strtolower($matches[0]);'
???????????),
???????????$line
???????);
???????echo?$line;
???}
???fclose($fp);
?>??
最后是
preg_split
(PHP?3?>=?3.0.9,?PHP?4,?PHP?5)
preg_split?--?用正則表達(dá)式分割字符串
不再贅述。
說明
array?preg_split?(?string?pattern,?string?subject?[,?int?limit?[,?int?flags]]?)
返回一個(gè)數(shù)組,包含?subject?中沿著與?pattern?匹配的邊界所分割的子串。?
如果指定了?limit,則最多返回?limit?個(gè)子串,如果?limit?是?-1,則意味著沒有限制,可以用來繼續(xù)指定可選參數(shù)?flags。?
flags?可以是下列標(biāo)記的任意組合(用按位或運(yùn)算符?|?組合):?
PREG_SPLIT_NO_EMPTY?
如果設(shè)定了本標(biāo)記,則?preg_split()?只返回非空的成分。?
PREG_SPLIT_DELIM_CAPTURE?
如果設(shè)定了本標(biāo)記,定界符模式中的括號表達(dá)式也會(huì)被捕獲并返回。本標(biāo)記添加于?PHP?4.0.5。?
PREG_SPLIT_OFFSET_CAPTURE?
如果設(shè)定了本標(biāo)記,如果設(shè)定本標(biāo)記,對每個(gè)出現(xiàn)的匹配結(jié)果也同時(shí)返回其附屬的字符串偏移量。注意這改變了返回的數(shù)組的值,使其中的每個(gè)單元也是一個(gè)數(shù)組,其中第一項(xiàng)為匹配字符串,第二項(xiàng)為其在?subject?中的偏移量。本標(biāo)記自?PHP?4.3.0?起可用。?
提示:?如果不需要正則表達(dá)式的功能,可以選擇使用更快(也更簡單)的替代函數(shù)如?explode()?或?str_split()。??

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
