PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

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


<?php
$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.

Need help with PHP? Post your question on our forum's PHP Group.
Facebook Twitter