0

I have the following string

$data = '
<tr>
    <td>Section Head 1</td>
    <td>DATA DATA DATA DATA 1</td>
</tr>
<tr>
    <td>Section Head 2</td>
    <td>DATA DATA DATA DATA 2</td>
</tr>';

I want to modify it to become like this:

<tr>
    <td width="25%;">Section Head 1</td>
    <td width="75%;">DATA DATA DATA DATA 1</td>
</tr>
<tr>
    <td width="25%;">Section Head 2</td>
    <td width="75%;">DATA DATA DATA DATA 2</td>
</tr>

I'm trying to use preg_replace('td', '$1 width="25%"', $data);

But I'm stuck, I cant figure out how to do this in a single preg_replace

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
RG Servers
  • 1,726
  • 2
  • 11
  • 27

1 Answers1

2

You can use a CSS property, and find even and odd occurrances in that pattern.

In this example, we have a table with the ID of myTable, where all the even children of <td> gets 25% width, odd children gets 75% width.

table#myTable tr td:nth-child(even) {
  width: 25%;
}
table#myTable tr td:nth-child(odd) {
  width: 75%;
}
<table id="myTable">
  <tr>
      <td>Section Head 1</td>
      <td>DATA DATA DATA DATA 1</td>
  </tr>
  <tr>
      <td>Section Head 2</td>
      <td>DATA DATA DATA DATA 2</td>
  </tr>
</table>

So you would do

<table id="myTable">
    <?php echo $data; ?>
</table>
Qirel
  • 25,449
  • 7
  • 45
  • 62