复制html代码的某些部分并在PHP中创建其他链接

时间:2014-12-26 10:13:43

标签: php html preg-match preg-match-all

我想在php中创建一个函数,我可以用一个例子来解释我想要的东西:

HTML CODE:

<?php
$html= '
<td id="rsO"><a href="./go.php?q=link"><img height="89" src="http://example.org/1.jpg" width="134"></a><br><cite title="default title">website</cite><br>a picture from america<br>567 × 378 - 47k&nbsp;-&nbsp;jpg</td>
<td id="rsO"><a href="./go.php?q=link"><img height="89" src="http://example.org/1.jpg" width="134"></a><br><cite title="default title">website</cite><br>a picture from germany<br>567 × 378 - 47k&nbsp;-&nbsp;jpg</td>
';
?>

结果:

<td id="rsO"><a href="./go.php?q=link&keyword=a picture from america"><img height="89" src="http://example.org/1.jpg" width="134"></a><br><cite title="default title">website</cite><br>a picture from america<br>567 × 378 - 47k&nbsp;-&nbsp;jpg</td>
<td id="rsO"><a href="./go.php?q=link&keyword=a picture from germany"><img height="89" src="http://example.org/1.jpg" width="134"></a><br><cite title="default title">website</cite><br>a picture from germany<br>567 × 378 - 47k&nbsp;-&nbsp;jpg</td>

如您所见来自美国的图片来自德国的图片会被复制到链接中:

...<br>a picture from america<br>...
<a href="./go.php?q=link&keyword=a picture from america">


...<br>a picture from germany<br>...
<a href="./go.php?q=link&keyword=a picture from germany">

有这样的千个html代码我想将所有这些代码复制到链接中而不会破坏。 感谢。

1 个答案:

答案 0 :(得分:0)

我不知道这有多有效但我希望有人可以做得更好

 <?php

$html = '
<td id="rsO"><a href="./go.php?q=link"><img height="89" src="http://example.org/1.jpg" width="134"></a><br><cite title="default title">website</cite><br>a picture from america<br>567 × 378 - 47k&nbsp;-&nbsp;jpg</td>
<td id="rsO"><a href="./go.php?q=link"><img height="89" src="http://example.org/1.jpg" width="134"></a><br><cite title="default title">website</cite><br>a picture from germany<br>567 × 378 - 47k&nbsp;-&nbsp;jpg</td>
';

$strs = array();
$strsCounter = 0;

function collect_keyword($matches) {
    global $strs;
    $strs[] = $matches[0];
    return $matches[0];
}

$patterns = array('/([A-Za-z\s-_]+(?!<\/cite><br>)(?=<br>\d*))/');
preg_replace_callback($patterns, collect_keyword, $html);

function generate_link($matches) {
    global $strs, $strsCounter;
    $return = $matches[0] . '&keyword=' . $strs[$strsCounter];
    $strsCounter++;
    return $return;
}

$patterns = array('/(\.\/go\.php\?q=link)/');
$line = preg_replace_callback($patterns, generate_link, $html);
echo '<table><tr>' . $line . '</tr></table>';
?>