-1

Regx is not my thing.

I have a large file where I want to replace the following example:

<g:id><![CDATA[131614-3XL]]></g:id>

should be replace with:

<g:id><![CDATA[131614-3XL]]></g:id><g:id2><![CDATA[131614]]></g:id2>

Please note that "-3XL" is deleted in id2 and please note that -3XL could be many other combinations. fx. -4XL or -32/32 or -42,5 and so on. But it always starts with -

I have tried using preg_replace but I can figure it out.

4
  • As long as "<g:id><![CDATA[131614-3XL]]></g:id>" doesn't change in the string that you want to replace, you can achieve that using a simple string replace, here is the documentation: php.net/manual/en/function.str-replace.php Commented Mar 3, 2023 at 16:21
  • 1
    Please add your preg_replace attempts. Commented Mar 3, 2023 at 16:22
  • @MarcelloPerri That won't work. please note that -3XL could be many other combinations Commented Mar 3, 2023 at 16:24
  • Don't use regular expressions to manipulate XML or HTML. Use DOMDocument. Commented Mar 3, 2023 at 16:53

2 Answers 2

0

Use a capture group to grab the number in the CDATA so you can copy it to the replacement without the -XXX after it.

$result = preg_replace('#<g:id><!\[CDATA\[(\d+)-[^]]+\]\]></g:id>#', '$0<g:id2><![CDATA[$1]]></g:id2>', $string);

$0 is the entire match, $1 is the number in the CDATA.

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

Here is code that you can start with. You might need to adjust depending upon how much the CDATA content changes.

$str = "<g:id><![CDATA[131614-3XL]]></g:id>";
$expected = "<g:id><![CDATA[131614-3XL]]></g:id><g:id2><![CDATA[131614]]></g:id2>";

# Get the first section without the g:id wrapper and without the -3XL section
$post_replace = preg_replace("/^<g:id>(.*?CDATA\[\d+)\-[^\]]+(.*?)<\/g:id>$/","$1$2", $str);

$output = "$str<g:id2>$post_replace</g:id2>";

if ($output == $expected) {
    print "Success\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.