1

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 = "&bull; 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 = "&bull; Something.
<table border="0"><tbody><tr><td>New Data</td></tr></tbody>/<table>
<br/>Something else;
4
  • Can you see that your quoted literals are not correct! Remember you cannot have a " inside a double quoted literal unless you escape it. Otherwise it closes the string literal Commented Sep 30, 2019 at 13:33
  • Alternatively make the string literal single quoted, then you can use double quotes inside it, or visa versa Commented Sep 30, 2019 at 13:33
  • Small Point The code you show does not even compile let alone work! Commented Sep 30, 2019 at 13:36
  • Why don't you simply replace the part with str_replace()? Commented Sep 30, 2019 at 14:24

1 Answer 1

3

As far as I see your strings are supposed to be a valid html. So you can work with them using DOMDocument.

$string1 = "&bull; 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.

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

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.