[ Note: Have you already pre-ordered your copy of our Printed Smashing Book #3? The book is a professional guide on how to redesign websites and it also introduces a whole new mindset for progressive Web design, written by experts for you.]
1. What are Regular ExpressionsThe main purpose of regular expressions, also called regex or regexp, is to efficiently search for patterns in a given text. These search patterns are written using a special format which a regular expression parser understands.
Regular expressions are originating from Unix systems, where a program was designed, called grep, to help users work with strings and manipulate text. By following a few basic rules, one can create very complex search patterns.
As an example, let’s say you’re given the task to check wether an e-mail or a telephone number has the correct form. Using a few simple commands these problems can easily be solved thanks to regular expressions. The syntax doesn’t always seems straightforward at first, but once you learn it, you’ll realize that you can do pretty complex searches easily, just by typing in a few characters and you’ll approach problems from a different perspective.
2. Perl Compatible Regular ExpressionsPHP has implemented quite a few regex functions which uses different parsing engines. There are two major parser in PHP. One called POSIX and the other PCRE or Perl Compatible Regular Expression.
The PHP function prefix for POSIX is ereg_. Since the release of PHP 5.3 this engine is deprecated, but let’s have a look at the more optimal and faster PCRE engine.
In PHP every PCRE function starts with preg_ such as preg_match or preg_replace. You can read the full function list in PHP’s documentation.
3. Basic SyntaxTo use regular expressions first you need to learn the syntax. This syntax consists in a series of letters, numbers, dots, hyphens and special signs, which we can group together using different parentheses.
In PHP every regular expression pattern is defined as a string using the Perl format. In Perl, a regular expression pattern is written between forward slashes, such as /hello/. In PHP this will become a string, ‘/hello/’.
Now, let’s have a look at some operators, the basic building blocks of regular expressions
^ | The circumflex symbol marks the beginning of a pattern, although in some cases it can be omitted |
$ | Same as with the circumflex symbol, the dollar sign marks the end of a search pattern |
. | The period matches any single character |
? | It will match the preceding pattern zero or one times |
+ | It will match the preceding pattern one or more times |
* | It will match the preceding pattern zero or more times |
| | Boolean OR |
- | Matches a range of elements |
() | Groups a different pattern elements together |
[] | Matches any single character between the square brackets |
{min, max} | It is used to match exact character counts |
\d | Matches any single digit |
\D | Matches any single non digit caharcter |
\w | Matches any alpha numeric character including underscore (_) |
\W | Matches any non alpha numeric character excluding the underscore character |
\s | Matches whitespace character |
As an addition in PHP the forward slash character is escaped using the simple slash \. Example: ‘/he\/llo/’
To have a brief understanding how these operators are used, let’s have a look at a few examples:
‘/hello/’ | It will match the word hello |
‘/^hello/’ | It will match hello at the start of a string. Possible matches are hello orhelloworld, but not worldhello |
‘/hello$/’ | It will match hello at the end of a string. |
‘/he.o/’ | It will match any character between he and o. Possible matches are heloor heyo, but not hello |
‘/he?llo/’ | It will match either llo or hello |
‘/hello+/’ | It will match hello on or more time. E.g. hello or hellohello |
‘/he*llo/’ | Matches llo, hello or hehello, but not hellooo |
‘/hello|world/’ | It will either match the word hello or world |
‘/(A-Z)/’ | Using it with the hyphen character, this pattern will match every uppercase character from A to Z. E.g. A, B, C… |
‘/[abc]/’ | It will match any single character a, b or c |
‘/abc{1}/’ | Matches precisely one c character after the characters ab. E.g. matchesabc, but not abcc |
‘/abc{1,}/’ | Matches one or more c character after the characters ab. E.g. matches abcor abcc |
‘/abc{2,4}/’ | Matches between two and four c character after the characters ab. E.g. matches abcc, abccc or abcccc, but not abc |
Besides operators, there are regular expression modifiers, which can globally alter the behavior of search patterns.
The regex modifiers are placed after the pattern, like this ‘/hello/i’ and they consists of single letters such as i which marks a pattern case insensitive or x which ignores white-space characters. For a full list of modifiers please visit PHP’s online documentation.
The real power of regular expressions relies in combining these operators and modifiers, therefore creating rather complex search patterns.
4. Using Regex in PHPIn PHP we have a total of nine PCRE functions which we can use. Here’s the list:
preg_filter ? performs a regular expression search and replace preg_grep ? returns array entries that match a pattern preg_last_error ? returns the error code of the last PCRE regex execution preg_match ? perform a regular expression match preg_match_all ? perform a global regular expression match preg_quote ? quote regular expression characters preg_replace ? perform a regular expression search and replace preg_replace_callback ? perform a regular expression search and replace using a callback preg_split ? split string by a regular expressionThe two most commonly used functions are preg_match and preg_replace.
Let’s begin by creating a test string on which we will perform our regular expression searches. The classical hello world should do it.
view plain copy to clipboard print ?
$test_string = 'hello world';If we simply want to search for the word hello or world then the search pattern would look something like this:
view plain copy to clipboard print ?
preg_match('/hello/', $test_string); preg_match('/world/', $test_string);If we wish to see if the string begins with the word hello, we would simply put the ^ character in the beginning of the search pattern like this:
view plain copy to clipboard print ?
preg_match('/^hello/', $test_string);Please note that regular expressions are case sensitive, the above pattern won’t match the word hElLo. If we want our pattern to be case insensitive we should apply the following modifier:
view plain copy to clipboard print ?
preg_match('/^hello/i', $test_string);Notice the character i at the end of the pattern after the forward slash.
Now let’s examine a more complex search pattern. What if we want to check that the first five characters in the string are alpha numeric characters.
view plain copy to clipboard print ?
preg_match('/^[A-Za-z0-9]{5}/', $test_string);Let’s dissect this search pattern. First, by using the caret character (^) we specify that the string must begin with an alpha numeric character. This is specified by [A-Za-z0-9].
A-Z means all the characters from A to Z followed by a-z which is the same except for lowercase character, this is important, because regular expressions are case sensitive. I think you’ll figure out by yourself what 0-9 means.
{5} simply tells the regex parser to count exactly five characters. If we put six instead of five, the parser wouldn’t match anything, because in our test string the word hello is five characters long, followed by a white-space character which in our case doesn’t count.
Also, this regular expression could be optimized to the following form:
view plain copy to clipboard print ?
preg_match('/^\w{5}/', $test_string);\w specifies any alpha numeric characters plus the underscore character (_).
6. Useful Regex FunctionsHere are a few PHP functions using regular expressions which you could use on a daily basis.
Validate e-mail. This function will validate a given e-mail address string to see if it has the correct form.
view plain copy to clipboard print ?
function validate_email($email_address) { if( !preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+ ([a-zA-Z0-9\._-]+)+$/", $email_address)) { return false; } return true; }Validate a URL
view plain copy to clipboard print ?
function validate_url($url) { return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)? (/.*)?$|i', $url); }Remove repeated words. I often found repeated words in a text, such as this this. This handy function will remove such duplicate words.
view plain copy to clipboard print ?
function remove_duplicate_word($text) { return preg_replace("/s(w+s)1/i", "$1", $text); }Validate alpha numeric, dashes, underscores and spaces
view plain copy to clipboard print ?
function validate_alpha($text) { return preg_match("/^[A-Za-z0-9_- ]+$/", $text); }Validate US ZIP codes
view plain copy to clipboard print ?
function validate_zip($zip_code) { return preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zip_code); } 7. Regex Cheat SheetBecause cheat sheets are cool nowadays, below you can find a PCRE cheat sheet that you can run through quickly anytime you forget something.
Meta Characters^ | Marks the start of a string |
$ | Marks the end of a string |
. | Matches any single character |
| | Boolean OR |
() | Group elements |
[abc] | Item in range (a,b or c) |
[^abc] | NOT in range (every character except a,b or c) |
\s | White-space character |
a? | Zero or one b characters. Equals to a{0,1} |
a* | Zero or more of a |
a+ | One or more of a |
a{2} | Exactly two of a |
a{,5} | Up to five of a |
a{5,10} | Between five to ten of a |
\w | Any alpha numeric character plus underscore. Equals to [A-Za-z0-9_] |
\W | Any non alpha numeric characters |
\s | Any white-space character |
\S | Any non white-space character |
\d | Any digits. Equals to [0-9] |
\D | Any non digits. Equals to [^0-9] |
i | Ignore case |
m | Multiline mode |
S | Extra analysis of pattern |
u | Pattern is treated as UTF-8 |
Author: Joel Reyes
Joel Reyes Has been designing and coding web sites for several years, this has lead him to be the creative mind behind Looney Designer a design resource and portfolio site that revolves around web and graphic design.
From: http://www.noupe.com/php/php-regular-expressions.html

PHPSession失效的原因包括配置錯誤、Cookie問題和Session過期。 1.配置錯誤:檢查並設置正確的session.save_path。 2.Cookie問題:確保Cookie設置正確。 3.Session過期:調整session.gc_maxlifetime值以延長會話時間。

在PHP中調試會話問題的方法包括:1.檢查會話是否正確啟動;2.驗證會話ID的傳遞;3.檢查會話數據的存儲和讀取;4.查看服務器配置。通過輸出會話ID和數據、查看會話文件內容等方法,可以有效診斷和解決會話相關的問題。

多次調用session_start()會導致警告信息和可能的數據覆蓋。 1)PHP會發出警告,提示session已啟動。 2)可能導致session數據意外覆蓋。 3)使用session_status()檢查session狀態,避免重複調用。

在PHP中配置會話生命週期可以通過設置session.gc_maxlifetime和session.cookie_lifetime來實現。 1)session.gc_maxlifetime控制服務器端會話數據的存活時間,2)session.cookie_lifetime控制客戶端cookie的生命週期,設置為0時cookie在瀏覽器關閉時過期。

使用數據庫存儲會話的主要優勢包括持久性、可擴展性和安全性。 1.持久性:即使服務器重啟,會話數據也能保持不變。 2.可擴展性:適用於分佈式系統,確保會話數據在多服務器間同步。 3.安全性:數據庫提供加密存儲,保護敏感信息。

在PHP中實現自定義會話處理可以通過實現SessionHandlerInterface接口來完成。具體步驟包括:1)創建實現SessionHandlerInterface的類,如CustomSessionHandler;2)重寫接口中的方法(如open,close,read,write,destroy,gc)來定義會話數據的生命週期和存儲方式;3)在PHP腳本中註冊自定義會話處理器並啟動會話。這樣可以將數據存儲在MySQL、Redis等介質中,提升性能、安全性和可擴展性。

SessionID是網絡應用程序中用來跟踪用戶會話狀態的機制。 1.它是一個隨機生成的字符串,用於在用戶與服務器之間的多次交互中保持用戶的身份信息。 2.服務器生成並通過cookie或URL參數發送給客戶端,幫助在用戶的多次請求中識別和關聯這些請求。 3.生成通常使用隨機算法保證唯一性和不可預測性。 4.在實際開發中,可以使用內存數據庫如Redis來存儲session數據,提升性能和安全性。

在無狀態環境如API中管理會話可以通過使用JWT或cookies來實現。 1.JWT適合無狀態和可擴展性,但大數據時體積大。 2.Cookies更傳統且易實現,但需謹慎配置以確保安全性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Atom編輯器mac版下載
最受歡迎的的開源編輯器

禪工作室 13.0.1
強大的PHP整合開發環境