preg_replace: add number after backreference

谁说胖子不能爱 提交于 2019-11-26 06:48:41

问题


Situation

I want to use preg_replace() to add a digit \'8\' after each of [aeiou].

Example

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.


回答1:


The solution is to wrap the backreference in ${}.

$out = preg_replace( '/([aeiou])/', '${1}8',  $in);

which will output a8bcde8fghi8j

See the manual on this special case with backreferences.




回答2:


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.



来源:https://stackoverflow.com/questions/18027811/preg-replace-add-number-after-backreference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!