PHP Regular Expressions

PHP Regular Expressions

Last Updated on Mar 22, 2023

What is Regular Expression?

A regular expression is a sequence of characters that specifies a search pattern. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.

You can read more at Wikipedia

The patterns are general and are not specific to php. You can learn and practice regex at regex101

Regular Expression in PHP

In php your regular expression should go between "//" so any pattern you have, would be something like this:

"/pattern/"

Check Patterns

Now let’s see how we can check that pattern against a string in php.

There are many functions but we are going to talk about 2 functions that are so useful and powerful

  • preg_match
  • preg_replace

Preg Match

preg_match(pattern, string,matches)

pattern: the regex pattern

string: where to search

matches: a variable you specify so if there were any matches those matches will be saved as an array in that variable.

Returns 1 if it finds the pattern and 0 if it dosn’t

$string = "Hello world! Hello Pratham! Hello Friends!";
$pattern = "/world/";

echo preg_match($pattern,$string,$matches);
// returns 1 because world exist

print_r($matches);
/* output is
Array
(
    [0] => world
)
*/

Preg Replace

preg_replace(pattern, replacements,input)

It’s like saying find all the matches and replace them

pattern: the regex pattern

replacements: can be a string or an array

input: can be a string or an array of strings

returns a string or an array of strings where the matched patterns have been replaced with the replacements

$string = "Hello world! Hello Pratham! Hello Friends!";
$pattern = "/Hello/";

$newString = preg_replace($pattern,"Goodbye",$string);
echo $newString;
/* output is
Goodbye world! Goodbye Pratham! Goodbye Friends!
*/
https://youtu.be/ZMACwe8S5Ow

Conclusion

Now you know about regular expressions in PHP.

I recommend you to open a PHP files and use both of the functions we learned to apply regex. see the result.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • regular expressions in PHP
  • preg replace
  • preg match

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts

Courses