-2

I'd like to replace the value in this tag using PHP's str_replace function:

<address2>Replace this value</address2>

What is the best approach to do this?

michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190
  • Possible duplicate of [Updating XML node with PHP](https://stackoverflow.com/questions/4748014/updating-xml-node-with-php) – Krzysztof Raciniewski Mar 19 '19 at 10:39
  • @KrzysztofRaciniewski Thanks for the reply. I'm not loading an XML file for this. However, I have found this which looks handy: http://php.net/manual/en/ref.simplexml.php – michaelmcgurk Mar 19 '19 at 10:42

3 Answers3

1

Try this :

$nodeAdresseValue = str_replace("%value%", "your value", "<address2>%value%</address2>");
c.brahim
  • 170
  • 1
  • 4
0

Do not use string functions on XML, use DOMDocument instead, it'll help you parse XML more easily, here is an example code DEMO:

<?php

$string = "<address2>Replace this value</address2>";
$domDocument = new DOMDocument();
$domDocument->loadXML($string);
$address2Elements = $domDocument->getElementsByTagName('address2');
foreach ($address2Elements as $address2) {
        $address2->nodeValue = "Value Replaced";

}

var_dump($domDocument->saveXML());

Output:

string(58) "<?xml version="1.0"?>
<address2>Value Replaced</address2>
"
mega6382
  • 9,211
  • 17
  • 48
  • 69
0
$search  = "/[^<address2>](.*)[^<\/address2>]/";
$replace = "replace with me";
$string  = "<address2>Replace this value </address2>";
echo preg_replace($search,$replace,$string);

this will work irrespective of the text, it will work even if you dont know the value inside tags

Ash-b
  • 705
  • 7
  • 11