PHP and MySQL (56 Blogs) Become a Certified Professional

How to build a regular expression in PHP?

Published on Jul 22,2019 1.8K Views

How to build a regular expression in PHP?

In order to simplify the identification of patterns in a string by using a single function which saves a lot of time to code. They are used in various things like creating a custom HTML template, validating user input like telephone numbers, email address, etc, highlighting the keywords in search results. In this Regular Expression in PHP article, you will learn the different functions in the following sequence:

Let’s get started.

What are Regular Expressions?

A Regular Expression is a sequence of characters that constructs a search pattern. When you search for data in a text, you can use this search pattern to describe what you are looking for.

 

regular expression - php regex - edureka

 

A regular expression can be a single character or a more complicated pattern. It can be used for any type of text search and text replace operations. A Regex pattern consist of simple characters, such as /abc/, or a combination of simple and special characters, such as /ab*c/ or  /example(d+).d*/.

Regular Expression in PHP

PHP has built-in functions that allow us to work with regular functions. Some of the commonly used regular expression functions in PHP are:

  • preg_match
  • preg_split 
  • preg_replace

Now let’s move ahead with the regular expressions in PHP and have a detailed look at the three functions.

What is preg_match?

 It is a function that is used for performing a pattern match on a string which returns true if a match is found else it returns false.

Syntax:

preg_match(pattern,input,matches,flags,offset)

Pattern: It is the pattern used for searching as a string.

Input: It is the input string

matches:  If some matches are provided, for getting filled with the search for results. $matches[0] will contain the text to be matched with the complete pattern, $matches[1] will contain the text which is matched with the first captured parenthesized subpattern and so on.

Example:




<pre>
<?php $var= 'ashokiscoder'; preg_match('/(ashok)(is)(coder)/', $var, $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?> 
</pre>

Output:

Array
(
    [0] => Array
        (
            [0] => ashokiscoder
            [1] => 0
        )
    [1] => Array
        (
            [0] => ashok
            [1] => 0
        )
    [2] => Array
        (
            [0] => is
            [1] => 5
        )
    [3] => Array
        (
            [0] => coder
            [1] => 7
        )
)

Now that you know how preg_match works, let’s move ahead with our Regular expression in PHP and have a look at the next function.

What is preg_split?

It is a function which is used for performing a pattern match on a string and then split the results into a numeric array.

Syntax:


array preg_split(pattern,subject,limit, flag)

pattern:  It is of string type for searching the pattern else it separates the elements.

subject: It is a variable that is used to store the input string.

limit: It indicates the limit. If the limit is specified, then sub-string has to be returned up to limit. If limit is 0 or -1, it indicates “no limit” which is used by a flag.

flag:  flags can be any of these following flags:

  • PREG_SPLIT_NO_EMPTY − Only non-empty pieces will be returned by preg_split()

  • PREG_SPLIT_DELIM_CAPTURE − Parenthesized expression in the delimiter pattern will be captured and returned as well.

  • PREG_SPLIT_OFFSET_CAPTURE − For every occurring match the appendant string offset will also be returned.

If you want to split the phrase by any number of commas or space characters:




<pre>
<?php $variable = preg_split("/[s,]+/", "ashok tarun, charan sabid"); print_r($variable); ?>
</pre>

Output:

Array
(
    [0] => ashok
    [1] => tarun
    [2] => charan
    [3] => sabid
)

In this way we split a string into component characters.




<pre>
<?php $var_string = 'ashok'; $var_char = preg_split('//', $var_string, -1, PREG_SPLIT_NO_EMPTY); print_r($var_char); ?>
</pre>

Output:

Array
(
    [0] => a
    [1] => s
    [2] => h
    [3] => o
    [4] => k
)

In this way, we split a string into matches and their offsets




<pre>
<?php $var_string = 'ashok is a student'; $var_char = preg_split('/ /', $var_string, -1, PREG_SPLIT_OFFSET_CAPTURE); print_r($var_char); ?>
</pre>

Output:

Array
(
    [0] => Array
        (
            [0] => ashok
            [1] => 0
        )
    [1] => Array
        (
            [0] => is
            [1] => 6
        )
    [2] => Array
        (
            [0] => a
            [1] => 9
        )
    [3] => Array
        (
            [0] => student
            [1] => 11
        )
)

Now let’s move ahead and check out the final function for Regular expression in PHP.

 

What is preg_replace?

It is a function that is used for performing a pattern match on a string and then replaces the match with the specified text.

Syntax:


preg_replace( pattern, replacement, subject, limit, count )

Pattern: It contains the string which is used to search the content which can be a string or array of string

Replacement: It specifies the string or array of strings to replace.

Subject: It is a string or an array of string to search or replace.

Limit: It specifies the maximum possible replacements for every pattern

count: It is an optional parameter which can be filled with a number of replacements done

In order to use backreferences by numeric literals:

<?php $string = 'July 07, 2019'; $pattern = '/(w+) (d+), (d+)/i'; $replacement = '${1}1,$3'; echo preg_replace($pattern, $replacement, $string); ?>

Output: 

July 1, 2019

In order to use index arrays with preg_replace()




<pre>
<?php $var_string = 'ashok'; $var_char = preg_split('//', $var_string, -1, PREG_SPLIT_NO_EMPTY); print_r($var_char); ?>
</pre>

Output:

The fish swims in sea.

With this we come to an end of this article, I hope you have learned about the commonly used regular expression functions in PHP which are  preg_match, preg_split, preg_replace.

Now with this, we have come to the end of the php regular expressions. I Hope you guys enjoyed this article and understood the regular expressions in PHP. So, with the end of this PHP Tutorial, you are no longer a newbie to the scripting language.

If you found this regular expression in PHP blog relevant, check out the PHP Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.

Got a question for us? Please mention it in the comments section of ”regular expression in PHP” and I will get back to you.

Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to build a regular expression in PHP?

edureka.co