一种更符合自然语意的PHP正则表达式
在編程的過程中,尤其是文本的處理,我們很多時候都需要正則表達式,比如,驗證用戶輸入的Email是否格式正確,電話號碼是否符合規范,或者其他的自定義規則。對新手來說,熟記正則表達式的規則比較困難,那么有沒有一種更符合自然語義的正則表達式呢,本文會
在編程的過程中,尤其是文本的處理,我們很多時候都需要正則表達式,比如,驗證用戶輸入的Email是否格式正確,電話號碼是否符合規范,或者其他的自定義規則。對新手來說,熟記正則表達式的規則比較困難,那么有沒有一種更符合自然語義的正則表達式呢,本文會給你答案。
Most newbie (and some seasoned) programmers have difficultly constructing Regular Expressions. Many a times one needs to create a Regexp quickly to test a a particular piece of code. However, not being comfortable withe Regexps can be a problem.?VerbalExpressions?is a PHP library that enables you to construct regular expressions using natural language like constructs. Think of it like a DSL for building Regexps.
verbalexpressions 已經實現了多個語言版本的庫,可以從這里得到。
Below is a sample PHP code that constructs a regular expression which tests whether a given string is a valid url.
如下示例用來測試給定的一個string是否是有效的url地址。
startOfLine()
->then("http")
->maybe("s")
->then("://")
->maybe("www.")
->anythingBut(" ")
->endOfLine();
if($regex->test("http://www.codediesel.com"))
echo "valid url";
else
echo "invalid url";
?>
登錄后復制
The main part of the code the DSL like interface that helps you build a Regexp.
$regex ->startOfLine()
->then("http")
->maybe("s")
->then("://")
->maybe("www.")
->anythingBut(" ")
->endOfLine();
登錄后復制
If you want to see what regular expression the code has built, we can use the?getRegex function of the class.
startOfLine()
->then("http")
->maybe("s")
->then("://")
->maybe("www.")
->anythingBut(" ")
->endOfLine();
echo $regex->getRegex();
登錄后復制
This will print the Regexp given below.
打印輸出正則表達式。
/^(http)(s)?(\:\/\/)(www\.)?([^ ]*)$/m
登錄后復制
We can now use the above Regexp in our code to accomplish the same thing as above.
$myRegexp = '/^(http)(s)?(\:\/\/)(www\.)?([^ ]*)$/m';
if (preg_match($myRegexp, 'http://www.codediesel.com')) {
echo 'valid url';
} else {
echo 'invalud url';
}
登錄后復制
We can also use the?$regex?object given in the above example directly in our code where the particular Regexp is required.
可以使用函數 getRegex 獲取正則表達式規則,或者直接可以用 $regex 對象,庫內部已經實現了轉換。
內部的轉換函數:
/**
* Object to string
*
* PHP Magic method to return a string representation of the object.
*
* @access public
* @return string
*/
????public function __toString()
????{
????????return $this->getRegex();
????}
登錄后復制
include_once('VerbalExpressions.php');
$regex = new VerEx;
$regex ->startOfLine()
->then("http")
->maybe("s")
->then("://")
->maybe("www.")
->anythingBut(" ")
->endOfLine();
if (preg_match($regex, 'http://www.codediesel.com')) {
echo 'valid url';
} else {
echo 'invalud url';
}
登錄后復制
The PHP version of VerbalExpressions is a port of the original JavaScript version,JSVerbalExpressions. Additional modifiers that will help you build regular expressions can be found?here.
文章節選:constructing-hard-regular-expressions-with-verbalexpressions
The post 一種更符合自然語意的PHP正則表達式 appeared first on 潤物無聲.
總結
以上是生活随笔為你收集整理的一种更符合自然语意的PHP正则表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mac OS是什么意思(mac版是什么意
- 下一篇: 两篇word文档怎么检测重复(Word无