SyntaxStudy
Sign Up
Home PHP Reference preg_match() / preg_replace()

preg_match() / preg_replace()

function

preg_match() performs a regex search returning match count; preg_replace() replaces regex matches.

Syntax

preg_match(string $pattern, string $subject, array &$matches = []): int|false

Example

php
<?php
if (preg_match('/^[\w.]+@[\w.]+\.[a-z]{2,}$/', 'user@example.com')) {
    echo 'Valid email';
}

preg_match('/(\d{4})-(\d{2})-(\d{2})/', '2024-01-15', $m);
echo $m[1]; // 2024

echo preg_replace('/\s+/', ' ', 'hello    world'); // 'hello world'