I have string
;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic;;Called by the Grave);;{card}(Secrets of Dark Magic;;Called by the Grave;;Secrets of Dark Magic)
I want to remove ;; in here {card}(Secrets of Dark Magic;;Called by the Grave) ( not ;; outside)
Result I want
;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic;Called by the Grave);;{card}(Secrets of Dark Magic;Called by the Grave;Secrets of Dark Magic)
I tried code below but it remove all ;; in string!
$search = ';;';
$string = preg_replace("/($search)/", ";", $string);
CodePudding user response:
We can use preg_replace_callback
here to target all text occurring within parentheses (...)
. Then, on each match, do a simple string replacement from ;;
to single ;
.
$input = ";{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic;;Called by the Grave);;{card}(Secrets of Dark Magic;;Called by the Grave;;Secrets of Dark Magic)";
$output = preg_replace_callback("/\(.*?\)/", function($matches) {
return str_replace(";;", ";", $matches[0]);
}, $input);
echo $input;
echo "\n";
echo $output;
This prints:
;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic;;Called by the Grave);;{card}(Secrets of Dark Magic;;Called by the Grave;;Secrets of Dark Magic)
;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic);;{card}(Secrets of Dark Magic;Called by the Grave);;{card}(Secrets of Dark Magic;Called by the Grave;Secrets of Dark Magic)