str_replace while retaining a variable value

I am pretty sure I need to use preg_replace rather than str_replace in this situation, but can someone show me an example of how I might achieve the following?

Here is an example of a string I need to replace. (note: the amount value will be different in every circumstance)


<surcharge><name>fuel</name><amount>25</amount></surcharge>

Here is the same string I would like after I do the replacement.


<fuelcharge>25</fuelcharge>

I would normally use str_replace, but I do not know how to retain the amount value (eg:25) which will vary from post to post, which is why I believe I need to use preg_replace, which I will admit - I have problems with.


str_replace("<surcharge><name>fuel</name><amount>25</amount></surcharge>", "<fuelcharge>25</fuelcharge>",$string);

Here’s a slightly different (more programatic) way of approaching it. :slight_smile:


<?php
$strXML = '<root>
	<name>Anthony</name>
	<surcharge>
		<name>fuel</name>
		<amount>25</amount>
	</surcharge>
</root>';


$objXml = new SimpleXMLElement($strXML);


$objXml->fuelcharge = $objXml->surcharge->amount;


unset($objXml->surcharge);


echo $objXml->asXML();


/*
	<?xml version="1.0"?>
	<root>
		<name>Anthony</name>
		<fuelcharge>25</fuelcharge>
	</root>
*/

Go with @Anthony’s version, much better.

I was curious to know if the htmlspecialchars(…) could be used within str_replace(…);

Hi,
I would choose to use preg_replace(). Like this:

$string = 'abc <surcharge><name>fuel</name><amount>25</amount></surcharge> xyz';

echo preg_replace('#<surcharge><name>fuel</name><amount>([0-9]*)</amount></surcharge>#i', '<fuelcharge>$1</fuelcharge>', $string);

@MarPlo: That is the quick solution, exactly what I was after - thanks.

@Anthony: Overall, that is a much better solution. I will be looking into that moving forward, thanks!