My PHP Regex Cheat Sheet
My PHP Regex Cheat Sheet
com/
Delimiter
Meta Characters
grouping:
() Group elements
(?!ab|cd).* Group of elements except ab or cd (this is negative lookahead)
named match:
repetition:
? 0 | 1
+ 1 | inf
* 0 | inf
matchings:
Modifiers
/.../uims
u Pattern is treated as UTF-8
x mogu se koristiti razmaci u patternu, bez da se match-aju (također i
comments #..., i newline, pa se može pisati jako lijep i pregledan regex)
i case insensitive
m multiline, ignores new line
s if included, the . character matches all characters, including newline
=================
preg_match
=================
- ie1:
if ( preg_match( $pattern, $subject ) == 1 ) { ... }
- ie2:
if ( preg_match( $pattern, $subject, $matches ) == 1 ) { ... }
=================
preg_split
=================
- explodira u array
- ie.
$txt = ',,text,other,,end.';
$words_Also_Empty_Arr = preg_split( '/,/', $txt, -1);
$words_Without_Empty_Arr = preg_split( '/,/', $txt, -1,
PREG_SPLIT_NO_EMPTY );
=================
preg_grep
=================
- radi regex nad elementima arraya i vraća array sa tim elementima
- ie.
$foods = array("pasta", "steak", "fish", "potatoes");
$p_foods_Arr = preg_grep("/p(\w+)/", $foods);
$non_p_foods_Arr = preg_grep("/p(\w+)/", $foods, PREG_GREP_INVERT);
=================
preg_quote
=================
- escapes every regex character
- ie.
$punctuation = preg_quote( "().-" );
echo $punctuation; // \(\)\.-.
=================
preg_replace
=================
- regex search and replace
$content_updated = null;
$content_updated = preg_replace( $pattern, $replace, $content );
if ( $content_updated && $content !== $content_updated ) {
...
}