如何使用 $1 两次

How to use $1 twice

我想知道如何使用(.*?)的值两次? 例如:

$data = preg_replace("/<d>\s*(\s*(.*?)\s*)</d>/i", "F: , S: ", $data);

上面的代码 returns 是我使用的值(例如:Hello)和 returns: F: , S: Hello,但我想要 return F: Hello, S: Hello

这是无效的代码:

"MySQLi\s*~\s*Escape\s*(\s*.*?\s*)", " = mysql_real_escape_string", "MySQLi~Escape('Hi');" 输出:

 = mysql_real_escape_string('Hi');

你需要的是U修饰符。

试试看 here:

$res = preg_replace("/MySQLi\s*~\s*Escape\s*((\s*.*?\s*))/U", " = mysql_real_escape_string", "MySQLi~Escape('Hi');");
var_dump($res);

输出:

string(41) "('Hi'); = mysql_real_escape_string('Hi');"

来自official PHP's documentations

U (PCRE_UNGREEDY)

This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by ?. It is not compatible with Perl. It can also be set by a (?U) modifier setting within the pattern or by a question mark behind a quantifier (e.g. .*?).