查找和替换函数


PHP Find and replace function

我需要一个正则表达式查找和替换,我有点卡住了。

基本上,我有一个包含几个<td>的表在每个<td>中,我有一个<img>

我需要复制<img>的宽度和高度,并将其放置在<td>

我一直在手动执行此操作,但是<td>的数量正在增长,并且需要很长时间。

我只是需要帮助做实际的查找和替换

任何想法?

—EDIT—

谢谢你的建议,我想我会走dom路线,因为我更了解它。我之前做过regex,它做了一个更简单的任务,所以就从那里开始。你帮我省了不少时间

您应该考虑使用PHP提供的DOMDocument类。

例子:

<?php
$doc = new DOMDocument;
$doc->loadHTMLFile('/path/to/file.html');
// Find the TD elements.
$tds = $doc->getElementsByTagName('td');
// If TD elements were found, loop through each one of them.
if ( ! empty($tds) )
  foreach ( $tds as $td )
  {
    // Find the IMG elements located inside that TD
    $imgs = $td->getElementsByTagName('img');
    // Find the style attribute of the TD just in case one already exists.
    $style = $td->getAttribute('style');
    // I'm not sure what to do if multiple images are found so instead of looping to many, make sure only 1 is found.
    if ( ! empty($imgs) && count($imgs) == 1 )
    {
      $height = $imgs->item(0)->getAttribute('height');
      $width = $imgs->item(0)->getAttribute('width');
      if ( ! empty($height) )
        $style .= 'height:' . $height . 'px;';
      if ( ! empty($width) )
        $style .= 'width:' . $width . 'px;';
      // Update the style attribute of the TD element.
      $td->setAttribute('style', $style);
    }
  }
// Save the HTML document.
$doc->saveHTMLFile('/path/to/newfile.html');

更新:

<html>
  <body>
    <table>
      <tr>
        <td><img src="test.png" height="100" width="100" /></td>
        <td>
          <p><img src="test2.png" height="100" /></p>
        </td>
      </tr>
    </table>
  </body>
</html>

:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
  <body>
    <table>
      <tr>
        <td style="height:100px;width:100px;"><img src="test.png" height="100" width="100"></td>
        <td style="height:100px;">
          <p><img src="test2.png" height="100"></p>
        </td>
      </tr>
    </table>
  </body>
</html>

试试这样:

preg_replace('/<td>(.*?)<img(.*?)width='"('d+)(.*?)height='"('d+)(.*?)<'/td>/','<td width="${3}" height="${5}">${1}<img${2}width="${3}${4}height="${5}${6}</td>', $html);

不使用正则表达式也可以做到这一点。试试这样做:

var images = document.getElementsByTagName('img');
for(var i=0, j=images.length; i<j; i++){
    images[i].parentNode.setAttribute('height', images[i].height);
    images[i].parentNode.setAttribute('width', images[i].width);
}

脚本假设除了上面提到的图像之外没有其他图像。