0

I need to preg_replace tr and td tags with divs that have specific classes.

<td align="center" valign="top">CONTENT</td> should be replaced with <div class="myCLass">CONTENT</div>

And same goes with tr tags. There may be style, class, id, align, height etc attributes inside the tags and they need to be replaced.

I am trying to convert table->tbody->tr->td to Bootstrap. So I need to change tr tags to <div class="row"> and td tags to <div class="col-lg-12"> and remove table, tbody tags.

This is what I've tried, but it didn't work:

$html = preg_replace('/<tr (.*?)<\/tr>/si', '<div class="myClass" $1</div>', $html); 

Input:

<table border="0" _mce_new="1">
  <tbody>
    <tr>
      <td align="center" valign="top">
        <img src="" class="img-responsive">
      </td>
      <td align="center" valign="top">
        <img src="" class="img-responsive">
      </td>
    </tr>
    <tr>
      <td align="center" valign="top">CONTENT 1</td>
      <td align="center" valign="top">CONTENT 2</td>
    </tr>
  </tbody>
</table>

Outout:

<div class ="row">
  <div class ="col-lg-12">
    <img src="" class="img-responsive">
  </div>
  <div class ="col-lg-12">
    <img src="" class="img-responsive">
  </div>
</div>
<div class ="row">
  <div class ="col-lg-12">
    CONTENT 1
  </div>
  <div class ="col-lg-12">
    CONTENT 2
  </div>
</div>

Well here is possible solution to my problem:

$html = preg_replace('/<td.*?>(.*?)<\/td>/i', '<div class="col-lg-12">$1</div>', $html);
$html = preg_replace('/<tr.*?>(.*?)<\/tr>/i', '<div class="row">$1</div>', $html);

And after that I remove table and tbody tags and it works that way pretty well.

But in addition I wanted to ask if it is possible to restructure the code like so:

first row: first td from first tr and first td from second tr

second row: second td from first tr and second td from second tr

etc...

1 Answers1

0

Remove the space after <tr. Your example input does not have a space there.

For your edited question: Assuming each row has the same number of td elements (call it ncols), you could use a loop to grab each of the td elements into an array and then loop through the array for i from 0 to the number of rows - 1, printing array[i] and array[i+ncols].

ooga
  • 15,423
  • 2
  • 20
  • 21