Jurij Jazdanov
Jurij Jazdanov

Reputation: 1258

Match multiple substrings and concatenate

Given I have

KsKd2s4dAs =AhAd2s4dKs =AsAd2s4dKs 5s5d6s6d2c AsAd6s6d2c =AdQdKdJdTd =AhQhKhJhTh =AsQsKsJsTs

I want to match all the substrings starting with '=' and concatenate them with this sign.

Output should be

KsKd2s4dAs AhAd2s4dKs=AsAd2s4dKs 5s5d6s6d2c AsAd6s6d2c AdQdKdJdTd=AhQhKhJhTh=AsQsKsJsTs

I am able to capture by using this regexp (=.{10}\s?)+ but failing to find a convenient way to make such string.

Upvotes: 1

Views: 96

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You can use

preg_replace('~(?:\G(?!\A)\s+(?==)|(?<!\S)=)(\S+)~', '$1', $text)

See the regex demo. Details:

  • (?:\G(?!\A)\s+(?==)|(?<!\S)=) - either a = char at the start of string or right after a whitespace or the end of the previous match and then one or more whitespaces followed with a = char
  • (\S+) - Group 1: one or more non-whitespace chars.

Another way is using preg_replace_callback:

$text = 'KsKd2s4dAs =AhAd2s4dKs =AsAd2s4dKs 5s5d6s6d2c AsAd6s6d2c =AdQdKdJdTd =AhQhKhJhTh =AsQsKsJsTs';
echo preg_replace_callback('~=(\S+(?:\s+=\S+)*)~', function($m) {
    return preg_replace('~\s+~', '', $m[1]);
}, $text);

See the PHP demo and the regex demo.

The =(\S+(?:\s+=\S+)*) matches a = and then captures into Group 1 any one or more non-whitespaces followed with zero or more repetitions of one or more whitespaces, =, and one or more non-whitespaces.

Upvotes: 2

Related Questions