Итак, первое, что нужно отметить, является то, что мы имеем массив шаблонов ($patterns
), и массив замен ($replace
). Давайте каждый шаблон и замена и разбить его:
Выкройка:
/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/
Замена:
\3/\4/\1\2
Это принимает дату и преобразует его из формата YYYY-M-D
в формат M/D/YYYY
.Давайте разберем это компоненты:
/ .../# The starting and trailing slash mark the beginning and end of the expression.
(19|20) # Matches either 19 or 20, capturing the result as \1.
# \1 will be 19 or 20.
(\d{2}) # Matches any two digits (must be two digits), capturing the result as \2.
# \2 will be the two digits captured here.
- # Literal "-" character, not captured.
(\d{2}) # Either 1 or 2 digits, capturing the result as \3.
# \3 will be the one or two digits captured here.
- # Literal "-" character, not captured.
(\d{2}) # Either 1 or 2 digits, capturing the result as \4.
# \4 will be the one or two digits captured here.
Этот матч заменяется \3/\4/\1\2
, что означает:
\3 # The two digits captured in the 3rd set of `()`s, representing the month.
/# A literal '/'.
\4 # The two digits captured in the 4rd set of `()`s, representing the day.
/# A literal '/'.
\1 # Either '19' or '20'; the first two digits captured (first `()`s).
\2 # The two digits captured in the 2nd set of `()`s, representing the last two digits of the year.
Выкройка:
/^\s*{(\w+)}\s*=/
Замена:
$\1 =
Это происходитимя переменной, кодированное как {variable}
, и преобразует ее в $variable = <date>
. Давайте разбить его:
/ .../# The starting and trailing slash mark the beginning and end of the expression.
^ # Matches the beginning of the string, anchoring the match.
# If the following character isn't matched exactly at the beginning of the string, the expression won't match.
\s* # Any whitespace character. This can include spaces, tabs, etc.
# The '*' means "zero or more occurrences".
# So, the whitespace is optional, but there can be any amount of it at the beginning of the line.
{ # A literal '{' character.
(\w+) # Any 'word' character (a-z, A-Z, 0-9, _). This is captured in \1.
# \1 will be the text contained between the { and }, and is the only thing "captured" in this expression.
} # A literal '}' character.
\s* # Any whitespace character. This can include spaces, tabs, etc.
= # A literal '=' character.
Этот матч заменяется $\1 =
, что означает:
$ # A literal '$' character.
\1 # The text captured in the 1st and only set of `()`s, representing the variable name.
# A literal space.
= # A literal '=' character.
Наконец, я хотел бы показать вам несколько ресурсов. Используемый вами формат regex называется «PCRE» или регулярными выражениями, совместимыми с Perl. Here - быстрый чит-лист на PCRE для PHP. За последние несколько лет появилось несколько инструментов, которые помогают визуализировать, объяснять и тестировать регулярные выражения. Один из них - Regex 101 (только Google «регулярное выражение» или «визуализатор регулярных выражений»). Если вы посмотрите here, это объяснение первого RegEx, а here - это объяснение второго. Есть и другие, такие как Debuggex, Regex Tester и т. Д. Но я считаю, что подробное разбиение по спине Regex 101 очень полезно.
Метасимвол \ w используется для поиска символа слова. + за одну или более, если m не ошибается – agpt
Отъезд [SO regex faq] (http://stackoverflow.com/a/22944075/3110638), [Rexegg Cheat Sheet] (http://www.rexegg.com/regex -quickstart.html), [пояснить regex] (http://rick.measham.id.au/paste/explain.pl), [regex101] (https://regex101.com/) (вставить regex> описание вверху справа) –