PHP TUTORIALPHP IntroductionPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP VariablesPHP ConstantsPHP OutputPHP Data TypesPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP StringsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms Finishing

Regex Introduction

Regex is a text-processing language! They are fast and efficient!

What is Regex?

Regex (or RegExp) stands for Regular Expressions, which is fast and efficient way to match patterns inside a string. In this tutorial, we will learn about how to create regular expressions and how to use them in PHP functions.

Regex can be used for processes like text search, text search and replace, input validation, etc.

Regex can be a simple character or a complicated pattern. All of these are defined under certain rules.

Regex in PHP

PHP supports the widely used syntax for regex: PCRE (Perl Compatible Regular Expressions) by default.

In PHP, PCRE functions are prefixed by preg_.

PHP Regex Replace Example

$str = 'Hello World';
$regex = '/\s/';
echo preg_replace($regex, '', $str);

Run Example ››

In this example, the first white space in "Hello World" is removed. So, it will output "HelloWorld". Let's see what $regex and preg_replace() does.

  • preg_replace() searches for a string (using regex patterns) and replaces it with another string.
  • $regex helps to search the string.
  • / signs at the beginning and ending of $regex indicates the start and the end of the regex. They are called delimiters.
  • \s is a single expression. It matches any white space characters. They are called character types.
  • Then, the match is replaced with ''. So, the whitespace gets removed.

We will learn more about PCRE syntax in the next chapter.