Home > Back-end >  Complicated text replace per line in PHP string
Complicated text replace per line in PHP string

Time:06-30

I have a string that contains lines like the following

<category id blabla>2</category>
...
<name>bloblo</name>
<category id blabla>35</category>

and an array like this

[2] => Shoes
[35] => T-Shirts

I want to scan every line that contains the word "category", putting the number between tags in a variable, so i can map it with the array and then replace the number with the name of the category.

I am trying to find an effective way to do this, as the string contains almost 12k lines. Tried with preg_split in foreach, but i am afraid the script crashes and i get no output (will try again tomorrow). Puting the XML code in simplexml_load_string neither seems to work (it works with smaller strings, but not with this one).

CodePudding user response:

You can try this:

foreach ($array as $key => $value) {
        $xml = str_replace(">" . $key . "</category>", ">" . $value . "</category>");
    }

Where $array is your mapping array and $xml is your xml. However this may not work for situations where you have spaces arround the value from the category tag, as they would need to be mapped separately. But if your xml respects the same format everywhere it should be ok.

CodePudding user response:

or this:

$str = '
<category id blabla>2</category>
...
<name>bloblo</name>
<category id blabla>35</category>';

$lines = explode("\n", $str);
$result = [];
$replacements = [
    '2' => "Shoes",
    '35' => "T-Shirts",
];

foreach ($lines as $line) {
    if (strrpos($line, '<category') === 0) {
        $a = explode(">", $line, 2);
        $b = explode("<", $a[1], 2);
        $num = $b[0];
        $replaced = $replacements[$num];
        $line = ($a[0] . ">" . $replaced . "<" . $b[1]);
    }
    $result[] = $line;
}

$final = implode("\n", $result);
echo "<xmp>" . $final . "</xmp>";

output:

<category id blabla>Shoes</category>
...
<name>bloblo</name>
<category id blabla>T-Shirts</category>
  • Related