hankknight
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:
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>
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>
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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;
?>
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
$html = str_get_html('<html><body>
// Find all tables with the CSS class of "mytable"
foreach($html->find('table
// For each found table, find the first <th> that has the scope="col" attribute
$th = $mytable->find('th[scope=c
$th->width = "20%"; // Set the <th> "width" attribute to "20%"
}
then output the modified structure:
echo $html->save();