Grayscale profile picture

Patrique Ouimet

Developer

PHP Common Regex

Wed, May 13, 2020 4:46 PM

This tip will contain common regex examples for PHP

This tip will be updated as I find more examples/scenarios that I discover and that may be useful to others.

Substring does not exist and substrings do exists

<?php

$sentences = [
    'This is foo example',
    'This is foo with bar example',
    'This is baz example',
    'This is baz with bar example',
    'This is bin example',
    'This is bin with bar example',
];

foreach ($sentences as $sentence) {
    if (preg_match('/^(?!.*bar).*(?:foo|baz|bin)/', $sentence)) {
        echo $sentence . PHP_EOL;
    }
}

// OUTPUT
// This is foo example
// This is baz example
// This is bin example

Alphanumeric Only

The example below will return only alphanumeric values (a to z and 0 to 9 case insensitive)

<?php

$sentences = [
    'Hello there!',
    '123-$&$*#(456@!$#@$#%$^%7890',
    'My order confirmation number is: AA12BB34CC56',
];

foreach ($sentences as $sentence) {
    echo preg_replace('/[^0-9a-zA-Z]/', '', $sentence) . PHP_EOL;
}

// OUTPUT
// Hellothere
// 1234567890
// MyorderconfirmationnumberisAA12BB34CC56

// With spaces
foreach ($sentences as $sentence) {
    echo preg_replace('/[^0-9a-zA-Z ]/', '', $sentence) . PHP_EOL;
}

// OUTPUT
// Hello there
// 1234567890
// My order confirmation number is AA12BB34CC56