PHP preg_replace - 如果匹配,则通过一次调用删除与正则表达式部分匹配的字符串的开头和结尾?
PHP preg_replace - in case of match remove the beginning and end of the string partly matched by regex with one call?
在 PHP 中,我尝试实现以下目标(如果可能,仅使用 preg_replace 函数):
示例:
$example1 = "\\\\\GLS\\\\\lorem ipsum dolor: T12////GLS////";
$example2 = "\\\GLS\\\hakunamatata ::: T11////GLS//";
$result = preg_replace("/(\)*GLS(\)*(.)*(\/)*GLS(\/)*/", "REPLACEMENT", $example1);
// current $result: REPLACEMENT (that means the regex works, but how to replace this?)
// desired $result
// for $example1: lorem ipsum dolor: T12
// for $example2: hakunamatata ::: T11
当然咨询过http://php.net/manual/en/function.preg-replace.php,但我的替换实验还没有成功。
这可以用一个 preg_replace 还是我必须拆分正则表达式并分别替换前匹配和后匹配?
如果正则表达式根本不匹配,我希望收到一个错误,但我可能会先用 preg_match 覆盖。
要点是用捕获组匹配和捕获你需要的东西,然后用对该组的反向引用替换。在您的正则表达式中,您将量词应用于组 ((.)*
),因此您无法访问整个子字符串,只有最后一个字符保存在该组中。
请注意 (.)*
匹配与 (.*)
相同的字符串,但在前一种情况下,您将在捕获组中有 1 个字符,因为正则表达式引擎会抓取一个字符并将其保存在缓冲区中,然后抓取另一个并重写前一个,依此类推。使用 (.*)
表达式,所有字符都被抓到一个块中,并作为一个完整的子字符串保存到缓冲区中。
这里有一个可行的方法:
$re = "/\\*GLS\\*([^\/]+)\/+GLS\/+/";
// Or to use fewer escapes, use other delimiters
// $re = "~\\*GLS\\*([^/]+)/+GLS/+~";
$str = "\\\GLS\\\hakunamatata ::: T11////GLS//";
$result = preg_replace($re, "", $str);
echo $result;
IDEONE demo 的结果:hakunamatata ::: T11
。
在 PHP 中,我尝试实现以下目标(如果可能,仅使用 preg_replace 函数):
示例:
$example1 = "\\\\\GLS\\\\\lorem ipsum dolor: T12////GLS////";
$example2 = "\\\GLS\\\hakunamatata ::: T11////GLS//";
$result = preg_replace("/(\)*GLS(\)*(.)*(\/)*GLS(\/)*/", "REPLACEMENT", $example1);
// current $result: REPLACEMENT (that means the regex works, but how to replace this?)
// desired $result
// for $example1: lorem ipsum dolor: T12
// for $example2: hakunamatata ::: T11
当然咨询过http://php.net/manual/en/function.preg-replace.php,但我的替换实验还没有成功。
这可以用一个 preg_replace 还是我必须拆分正则表达式并分别替换前匹配和后匹配?
如果正则表达式根本不匹配,我希望收到一个错误,但我可能会先用 preg_match 覆盖。
要点是用捕获组匹配和捕获你需要的东西,然后用对该组的反向引用替换。在您的正则表达式中,您将量词应用于组 ((.)*
),因此您无法访问整个子字符串,只有最后一个字符保存在该组中。
请注意 (.)*
匹配与 (.*)
相同的字符串,但在前一种情况下,您将在捕获组中有 1 个字符,因为正则表达式引擎会抓取一个字符并将其保存在缓冲区中,然后抓取另一个并重写前一个,依此类推。使用 (.*)
表达式,所有字符都被抓到一个块中,并作为一个完整的子字符串保存到缓冲区中。
这里有一个可行的方法:
$re = "/\\*GLS\\*([^\/]+)\/+GLS\/+/";
// Or to use fewer escapes, use other delimiters
// $re = "~\\*GLS\\*([^/]+)/+GLS/+~";
$str = "\\\GLS\\\hakunamatata ::: T11////GLS//";
$result = preg_replace($re, "", $str);
echo $result;
IDEONE demo 的结果:hakunamatata ::: T11
。