Reputation: 41
I'm trying to replace a part of a string with another but the part im trying to replace has table HTML tags.
$string1 = "• Somethig.
<table border="0"><tbody><tr><td>New Data</td></tr></tbody>/<table>
<br/>Something else;
$string2 = "• Somethig.
<table border="0"><tbody><tr><td>Old Data</td></tr></tbody>/<table>
<br/>Something else;
I tried this:
$firstarray = explode("table", $string1);
$secarray = explode("table", $string2);
$firstarray
(
[0] => something
[1] => New Data
[2] => something else
)
$secarray
(
[0] => something
[1] => Old Data
[2] => something else
)
$need = $firstarray[1];
$replace = $secarray[1];
$result = str_replace($replace, $need, $string2);
echo $result; // New Data
This works but I can't figure out how I'm going to make $string2 like this:
$string2 = "• Something.
<table border="0"><tbody><tr><td>New Data</td></tr></tbody>/<table>
<br/>Something else;
Upvotes: 1
Views: 863
Reputation: 978
As far as I see your strings are supposed to be a valid html. So you can work with them using DOMDocument
.
$string1 = "• Somethig.
<table border='0'><tbody><tr><td>Old Data</td></tr></tbody>/<table>
<br/>Something else;";
$dom = new DOMDocument;
$dom->loadHTML($string1);
$tds = $dom->getElementsByTagName('td');
foreach($tds as $td) {
$td->noveValue = 'New Data';
}
echo $dom->saveHTML();
Of course, code will depend on complexity of your html, but main idea is here.
Upvotes: 3