php - What are colons for in a preg_match pattern? -
in following php code (not mine):
$has_trailing_slash = preg_match(':/$:', $string);
what purpose of colons? if remove them, preg_match call complains if there isn't trailing slash in string. colons, preg_match doesn't complain if there isn't trailing slash. apparently colons kind of conditional or optional indicator, documented anywhere? can't find 1 word of documentation using colons way preg_match, or regex in general.
the colons here used delimiters.
you need use delimiters regex in php regex engine can know regex starts , regex ends, , excluding quotes use in function.
this particularly important regex engine can distinguish between actual regular expression , flags (if any) used (e.g. i
(for case insensitive matching), s
(to make dot match newlines), u
(to allow unicode character matching), etc)
you can use variety of delimiters , can use 'suitable' 1 depending on situation. instance, common delimiter use forward slash: /
. when use forward slash delimiter, have escape forward slashes in regular expression (by using backslash).
otherwise, can change delimiter , said, can use a delimiter such #
, or !
or |
or ~
or {}
, on, long it's not alphanumeric or backslash.
this means can use:
preg_match(':/$:', $string); preg_match('"/$"', $string); preg_match('@/$@', $string); preg_match('{/$}', $string);
but if use /
, you'll have escape /
in regex so:
preg_match('/\/$/', $string); # either use backslash preg_match('/[/]$/', $string); # or wrap around square brackets
or weird this:
preg_match('\'/$\'', $string);
using confuse people reading code , regex can considered confusing enough!
conclusion, have wide variety of delimiters choose from, it's preferable if consistent , try not make code confusing.
Comments
Post a Comment