Skip to content

Instantly share code, notes, and snippets.

@ManiruzzamanAkash
Last active June 5, 2021 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ManiruzzamanAkash/ad1f14aa998557cddf7597d18468637b to your computer and use it in GitHub Desktop.
Save ManiruzzamanAkash/ad1f14aa998557cddf7597d18468637b to your computer and use it in GitHub Desktop.
All Possible basic to advance level regex pattern example in depth example
<?php
/** EXAMPLE 1: With Digit check **/
echo "Digit Check\n-------------------\n";
// Basic Concept : /pattern/i
// / : start delimeter
// pattern : Here will be the pattern, [ eg: \d - Check if one digit match and then space ]
// i :for case insensitive [ eg: mg, mgi, i, m ]
$matches = []; // Matches array will be stored here
$string = "123";
$pattern = "/\d\d/i"; // pattern for two digit at a same time
$is_matched = preg_match( $pattern, $string, $matches ); // Check if matched or not
print_r( $is_matched ); /** Output: 1 **/
echo "\n";
print_r( $matches ); // Print all the matches as array
/** Output: **/
// Array
// (
// [0] => 12
// )
/** EXAMPLE 2: **/
echo "\n-------------------\nWord Check\n-------------------\n";
$matches = [];
$string = "akash";
$pattern = "/\w+/i"; // w+ : w=word start, + => till upto a space/new line
$is_matched = preg_match( $pattern, $string, $matches );
print_r( $is_matched );
echo "\n";
print_r( $matches );
/** Output **/
// -------------------
// Word Check
// -------------------
// 1
// Array
// (
// [0] => akash
// )
/** EXAMPLE 3: **/
echo "\n-------------------\nRange Example\n-------------------\n";
$matches = [];
$string = "123456";
$pattern = "/[3-9]/i"; // [3-9] =>> Find one character from this range of 3 to 9
$is_matched = preg_match( $pattern, $string, $matches );
print_r( $is_matched );
echo "\n";
print_r( $matches );
/** Output **/
//-------------------
//Range Example
//-------------------
// 1
// Array
// (
// [0] => 3
// )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment