php regex - replace on "\${1}"
found this regex:
insert " " every 10 characters: 开发者_StackOverflow社区
$text = preg_replace("|(.{10})|u", "\${1}"." ", $text);
can you, please, explain what \${1}
means. Why using \
and what curly brackets means?
Quoting some portions of the manual page of preg_replace
:
replacement
may contain references of the form\\n
or$n
, with the latter form being the preferred one.
You are, apparently, in the second case : $n
And, later :
When working with a replacement pattern where a backreference is immediately followed by another number (i.e.: placing a literal number immediately after a matched pattern), you cannot use the familiar
\\1
notation for your backreference.\\11
, for example, would confusepreg_replace()
since it does not know whether you want the\\1
backreference followed by a literal1
, or the\\11
backreference followed by nothing.
In this case the solution is to use\${1}1
. This creates an isolated$1
backreference, leaving the1
as a literal.
Here, you don't have anything after what would be $1
-- but I suppose it cannot hurt to use the \${1}
notation : I find it makes code easier to read, having those {}
; and it makes sure you won't forget to add them the day they are needed.
The first curly bracket is responsible for the counting of the characters. .{10}
means: 10 times any character.
The \${1} represents everything that is matched in the first pair of parantheses.
So, to paraphrase it: "Substitute the ten characters (.{10}
) with the same 10 characters (\${1}
) plus a space.
精彩评论