PHP Version
4+
// Example: Check if an email address has a valid format
$email = 'codingcourses@example.com';
$pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';

if (preg_match($pattern, $email)) {
    echo 'The email address has a valid format.';
} else {
    echo 'The email address does not have a valid format.';
}

// Output: 'The email address has a valid format.'
preg_match(
    string $pattern,
    string $subject,
    array &$matches = null,
    int $flags = 0,
    int $offset = 0
): int|false

/* preg_match(
    regular expression pattern,
    the string to search,
    array to store matching results[, 
    optional flags for additional settings[,
    offset in the string to start searching]]
   );
*/
$text = 'The price is 500 dollars.';
$pattern = '/\d+/';

if (preg_match($pattern, $text, $matches)) {
    echo 'Found number: ' . $matches[0];
} else {
    echo 'No number found.';
}

// Output: 'Found number: 500'
$url = 'https://www.example.com/page';
$pattern = '/https:\/\/(www\.)?([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,6})\/([a-zA-Z0-9.-\/]*)/';

if (preg_match($pattern, $url, $matches)) {
    $domain = $matches[2];
    echo 'Extracted domain: ' . $domain;
} else {
    echo 'No domain found.';
}

// Output: 'Extracted domain: example'
$text = 'A phone number in the string could be 123-456-7890.';
$pattern = '/\b(?:\d{2,3}[-.])?\d{3,4}[-.]\d{4}\b/';

if (preg_match($pattern, $text, $matches)) {
    $phoneNumber = $matches[0];
    echo 'Extracted phone number: ' . $phoneNumber;
} else {
    echo 'No phone number found.';
}

// Output: 'Extracted phone number: 123-456-7890'
$text = 'Hello, World!';
$pattern = '/hello/i';

if (preg_match($pattern, $text, $matches)) {
    echo 'Found a match regardless of case: ' . $matches[0];
} else {
    echo 'No matching string found.';
}

// Output: 'Found a match regardless of case: Hello'
$str = 'Hello, World!';
$substring = 'Hello';

$pos = strpos($str, $substring);

if ($pos === false) {
    echo 'The string does not contain "Hello".';
} else {
    echo 'The string contains "Hello".';
}

// Output: 'The string contains "Hello".'