首页 后端开发 php教程 Getting Started with PHP Regular Expressions

Getting Started with PHP Regular Expressions

Jun 23, 2016 pm 02:30 PM

[ 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 Expressions

The 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 Expressions

PHP 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 Syntax

To 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

Operator Description
^ 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:

Example Description
‘/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 PHP

In 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 expression

The 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 Functions

Here 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 Sheet

Because 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   Description
^ 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]
Pattern Modifiers   Description
i Ignore case
m Multiline mode
S Extra analysis of pattern
u Pattern is treated as UTF-8
8. Useful Readings 15 PHP Regular Expression for Web Developers Mastering Regular Expressions in PHP Introduction to PHP Regex

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

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

在Laravel中使用Flash会话数据 在Laravel中使用Flash会话数据 Mar 12, 2025 pm 05:08 PM

Laravel使用其直观的闪存方法简化了处理临时会话数据。这非常适合在您的应用程序中显示简短的消息,警报或通知。 默认情况下,数据仅针对后续请求: $请求 -

php中的卷曲:如何在REST API中使用PHP卷曲扩展 php中的卷曲:如何在REST API中使用PHP卷曲扩展 Mar 14, 2025 am 11:42 AM

PHP客户端URL(curl)扩展是开发人员的强大工具,可以与远程服务器和REST API无缝交互。通过利用Libcurl(备受尊敬的多协议文件传输库),PHP curl促进了有效的执行

简化的HTTP响应在Laravel测试中模拟了 简化的HTTP响应在Laravel测试中模拟了 Mar 12, 2025 pm 05:09 PM

Laravel 提供简洁的 HTTP 响应模拟语法,简化了 HTTP 交互测试。这种方法显着减少了代码冗余,同时使您的测试模拟更直观。 基本实现提供了多种响应类型快捷方式: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

在Codecanyon上的12个最佳PHP聊天脚本 在Codecanyon上的12个最佳PHP聊天脚本 Mar 13, 2025 pm 12:08 PM

您是否想为客户最紧迫的问题提供实时的即时解决方案? 实时聊天使您可以与客户进行实时对话,并立即解决他们的问题。它允许您为您的自定义提供更快的服务

解释PHP中晚期静态结合的概念。 解释PHP中晚期静态结合的概念。 Mar 21, 2025 pm 01:33 PM

文章讨论了PHP 5.3中引入的PHP中的晚期静态结合(LSB),从而允许静态方法的运行时分辨率调用以获得更灵活的继承。 LSB的实用应用和潜在的触摸

框架安全功能:防止漏洞。 框架安全功能:防止漏洞。 Mar 28, 2025 pm 05:11 PM

文章讨论了框架中的基本安全功能,以防止漏洞,包括输入验证,身份验证和常规更新。

自定义/扩展框架:如何添加自定义功能。 自定义/扩展框架:如何添加自定义功能。 Mar 28, 2025 pm 05:12 PM

本文讨论了将自定义功能添加到框架上,专注于理解体系结构,识别扩展点以及集成和调试的最佳实践。

See all articles