Nikita Gavrilov
Nikita Gavrilov

Reputation: 547

How to replace commas inside of brackets with preg_replace

I need to replace "," to "enoComma", but only that located inside of brackets <...>.
I'm trying to do it like this, but it replaces only the first comma inside of the brackets

$text = 'asd, asd <asd, asd, adasd> ... ';
preg_replace_callback("/(<.*?),(.*?>)/",
    create_function('$m', 'return $m[1].\'enoComma\'.$m[2];'),
    $text
);
echo $text; // asd, asd <asdenoComma asd, adasd> ... 

Upvotes: 1

Views: 880

Answers (2)

SDwarfs
SDwarfs

Reputation: 3239

I think this should do it:

$text = 'asd, asd <asd, asd, adasd> ... <a,b,c>';

function replace_function($s) {
  return str_replace(",", "enoComma", $s[0]);
}

$text = preg_replace_callback("|<(.*)>|", "replace_function", $text);

echo "$text\n";

Output:

asd, asd <asdenoComma asdenoComma adasd> ... <aenoCommabenoCommac>

Upvotes: 2

VolkerK
VolkerK

Reputation: 96159

Since you're already using preg_replace_callback I'd let it fetch everything between the brackets and then let the callback replace each comma by enoComma.

<?php
$text = 'asd, asd <asd, asd, adasd> asd, asd asd, asd <x, y, z> asd';
$text = preg_replace_callback('/(?<=<)[^<>]+(?=>)/', function($e) {
    return str_replace(',', 'enoComma', $e[0]);
}, $text);
echo $text;

prints

asd, asd <asdenoComma asdenoComma adasd> asd, asd asd, asd <xenoComma yenoComma z> asd

but keep in mind that this won't work with nested brackets like a,b<c,d<e,f>>
The example uses a lambda function instead of create_function.

Upvotes: 1

Related Questions