Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

PHP/REGEX: Set width of first th

Using PHP and preg_replace, I want to set the width of the first column in my table to 20%.

This:
<table class="mytable">
<thead>
<tr>
<th scope="col">
First Column</th>
<th scope="col" class="textright">
Second COlumn</th>
<th scope="col">
Third Column</th>
</tr>
</thead>
</table>

Open in new window

Should become this:

<table class="mytable">
<thead>
<tr>
<th scope="col" width="20%">
First Column</th>
<th scope="col" class="textright">
Second COlumn</th>
<th scope="col">
Third Column</th>
</tr>
</thead>
</table>

Open in new window

SOLUTION
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
By the way, if you use the Simple HTML DOM Parser, your code would look something like:

$html = str_get_html('<html><body>...<table class="mytable">...etc...</table>...</body></html>');

// Find all tables with the CSS class of "mytable"
foreach($html->find('table.mytable) as $mytable) {

     // For each found table, find the first <th> that has the scope="col" attribute
     $th     = $mytable->find('th[scope=col]', 0);
     $th->width = "20%"; // Set the <th> "width" attribute to "20%"
 }

then output the modified structure:
echo $html->save();
Avatar of hankknight

ASKER

Why doesn't this work?
<?php

header('Content-Type:text/plain'); 

$str = '
<table>
<thead>
<tr>
<th>
Col 1</th>
<th>
Col 2</th>
<th>
Col 3</th>
</tr>
</thead>
</table>
';

$str = preg_replace('/<th/', '<th width="100%" ', $str, 1); 

echo $str;

?>

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial