Skip to content

Instantly share code, notes, and snippets.

@simongcc
Last active February 15, 2022 10:59
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 simongcc/a2131ff35860e4e73b975e8e01e61e20 to your computer and use it in GitHub Desktop.
Save simongcc/a2131ff35860e4e73b975e8e01e61e20 to your computer and use it in GitHub Desktop.
PHP regular expression pattern reference
<?php
// Reference:
// https://stackoverflow.com/questions/48158544/how-to-separate-string-to-number-in-single-word-with-php.
// https://stackoverflow.com/questions/4311156/how-to-separate-letters-and-digits-from-a-string-in-php/4311416#4311416.
// https://stackoverflow.com/questions/26406756/diference-between-preg-replace-0-9-or-d-or-d.
// Testing playground: https://www.phpliveregex.com/#tab-preg-split.
// Match Digit + non-digit pattern.
// For pattern: numbers + unit, both example works.
$arr = mb_split('^[0-9]+\K',$str); // [0-9] could be replaced using \d instead.
// Or
$arr = preg_split('/^[0-9]+\K/',$str);
// Explanation
// ^ "Beginning with" is optional, depends on use case.
// [0-9]+, any digits with + any occurrence
// \K Lookbehind, restart the fullstring match, without this, the digits part will not be returned after split.
// The digit part will be used as the delimiter to split the string.
// Match specific prefixed words.
// ^pa_\K.+ eg match pa_XXXXX and put XXXXX in the result array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment