简体   繁体   English

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?

In PHP I try to achive the following (if possible only with the preg_replace function): 在PHP中,我尝试实现以下目标(如果可能,仅使用preg_replace函数):

Examples: 例子:

$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

Have consulted http://php.net/manual/en/function.preg-replace.php of course but my experiments with replacement have not been successful yet. 当然已经参考了http://php.net/manual/en/function.preg-replace.php ,但是我的替换实验还没有成功。

Is this possible with one single preg_replace or do I have to split the regular expression and replace the front match and the back match seperatly? 是否可以使用一个preg_replace来实现,还是我必须拆分正则表达式并分别替换前匹配和后匹配?

If the regex does not match at all I like to receive an error but this i may cover with preg_match first. 如果正则表达式根本不匹配,我想收到一个错误,但是我可能会先用preg_match进行介绍。

The main point is to match and capture what you need with a capturing group and then replace with the back-reference to that group. 要点是与捕获组匹配并捕获您需要的内容,然后替换为对该组的反向引用。 In your regex, you applied a quantifier to the group ( (.)* ) and thus you lost access to the whole substring, only the last character is saved in that group. 在您的正则表达式中,您对组( (.)* )应用了一个量词,因此您无法访问整个子字符串,只有最后一个字符保存在该组中。

Note that (.)* matches the same string as (.*) , but in the former case you will have 1 character in the capture group as the regex engine grabs a character and saves it in the buffer, then grabs another and re-writes the previous one and so on. 请注意, (.)*(.*)匹配相同的字符串,但是在前一种情况下,捕获组中将有1个字符,因为正则表达式引擎将捕获一个字符并将其保存在缓冲区中,然后捕获另一个字符并重新写上一个,依此类推。 With the (.*) expression, all the characters are grabbed together in one chunk and saved into the buffer as one whole substring. 使用(.*)表达式,所有字符将被一起抓成一个块,并作为一个完整的子字符串保存到缓冲区中。

Here is a possible way: 这是一种可能的方法:

$re = "/\\\\*GLS\\\\*([^\\/]+)\\/+GLS\\/+/"; 
// Or to use fewer escapes, use other delimiters
// $re = "~\\\\*GLS\\\\*([^/]+)/+GLS/+~"; 
$str = "\\\\\\GLS\\\\\\hakunamatata ::: T11////GLS//"; 
$result = preg_replace($re, "$1", $str);
echo $result;

Result of the IDEONE demo : hakunamatata ::: T11 . IDEONE演示的结果: hakunamatata ::: T11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM