Blackbam
Blackbam

Reputation: 19376

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):

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.

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?

If the regex does not match at all I like to receive an error but this i may cover with preg_match first.

Upvotes: 1

Views: 1786

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626927

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. 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.

Upvotes: 3

Related Questions