Situation
情况
I want to use preg_replace()
to add a digit '8'
after each of [aeiou]
.
Example
我想使用preg_replace()在每个[aeiou]之后添加一个数字“8”。例子
from
从
abcdefghij
to
来
a8bcde8fghi8j
Question
问题
How should I write the replacement string?
我应该如何写替换字符串?
// input string
$in = 'abcdefghij';
// this obviously won't work ----------↓
$out = preg_replace( '/([aeiou])/', '\18', $in);
This is just an example, so suggesting str_replace()
is not a valid answer.
I want to know how to have number after backreference in the replacement string.
这只是一个示例,因此建议str_replace()不是有效答案。我想知道如何在替换字符串中有回引用后的数字。
2 个解决方案
#1
18
The solution is to wrap the backreference in ${}
.
解决方案是用${}包装回引用。
$out = preg_replace( '/([aeiou])/', '${1}8', $in);
which will output a8bcde8fghi8j
将输出a8bcde8fghi8j
See the manual on this special case with backreferences.
请参阅关于此特殊情况的手册,其中包含反向引用。
#2
4
You can do this:
你可以这样做:
$out = preg_replace('/([aeiou])/', '${1}' . '8', $in);
Here is a relevant quote from the docs regarding backreference:
以下是文件的相关引用:
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 confuse preg_replace() since it does not know whether you want the \1 backreference followed by a literal 1, or the \11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.
当使用一个替换模式时,一个反向引用紧接着是另一个数字(即::在匹配的模式之后立即放置一个文字数字),您不能使用熟悉的\1表示法进行反向引用。例如,\11会混淆preg_replace(),因为它不知道您是想要用后跟文字1的\1的backreference,还是用不带文字1的\11的backreference。在这种情况下,解决方案是使用\${1}1。这将创建一个单独的$1回引用,将1保留为文字。
#1
18
The solution is to wrap the backreference in ${}
.
解决方案是用${}包装回引用。
$out = preg_replace( '/([aeiou])/', '${1}8', $in);
which will output a8bcde8fghi8j
将输出a8bcde8fghi8j
See the manual on this special case with backreferences.
请参阅关于此特殊情况的手册,其中包含反向引用。
#2
4
You can do this:
你可以这样做:
$out = preg_replace('/([aeiou])/', '${1}' . '8', $in);
Here is a relevant quote from the docs regarding backreference:
以下是文件的相关引用:
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 confuse preg_replace() since it does not know whether you want the \1 backreference followed by a literal 1, or the \11 backreference followed by nothing. In this case the solution is to use \${1}1. This creates an isolated $1 backreference, leaving the 1 as a literal.
当使用一个替换模式时,一个反向引用紧接着是另一个数字(即::在匹配的模式之后立即放置一个文字数字),您不能使用熟悉的\1表示法进行反向引用。例如,\11会混淆preg_replace(),因为它不知道您是想要用后跟文字1的\1的backreference,还是用不带文字1的\11的backreference。在这种情况下,解决方案是使用\${1}1。这将创建一个单独的$1回引用,将1保留为文字。