【发布时间】:2011-10-13 16:43:49
【问题描述】:
我需要在一些 html 代码的一部分中找到链接,并将所有链接替换为两个不同的绝对或基本域,然后是页面上的链接...
我找到了很多想法并尝试了很多不同的解决方案。在这个问题上我没有运气。请帮帮我!! 谢谢!!
这是我的代码:
<?php
$url = "http://www.oxfordreference.com/views/SEARCH_RESULTS.html?&q=android";
$raw = file_get_contents($url);
$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
$content = str_replace($newlines, "", html_entity_decode($raw));
$start = strpos($content,'<table class="short_results_summary_table">');
$end = strpos($content,'</table>',$start) + 8;
$table = substr($content,$start,$end-$start);
echo "{$table}";
$dom = new DOMDocument();
$dom->loadHTML($table);
$dom->strictErrorChecking = FALSE;
// Get all the links
$links = $dom->getElementsByTagName("a");
foreach($links as $link) {
$href = $link->getAttribute("href");
echo "{$href}";
if (strpos("http://oxfordreference.com", $href) == -1) {
if (strpos("/views/", $href) == -1) {
$ref = "http://oxfordreference.com/views/"+$href;
}
else
$ref = "http://oxfordreference.com"+$href;
$link->setAttribute("href", $ref);
echo "{$link->getAttribute("href")}";
}
}
$table12 = $dom->saveHTML;
preg_match_all("|<tr(.*)</tr>|U",$table12,$rows);
echo "{$rows[0]}";
foreach ($rows[0] as $row){
if ((strpos($row,'<th')===false)){
preg_match_all("|<td(.*)</td>|U",$row,$cells);
echo "{$cells}";
}
}
?>
当我运行此代码时,我得到 htmlParseEntityRef: Expecting ';'警告我加载 html 的行
【问题讨论】:
-
给我们一些示例 HTML,并告诉我们您希望它变成什么样子。向我们展示您的编码工作!你想用 PHP 还是 JavaScript 来做?
-
当您说“运气不在我这边”时,这是否意味着您找到了 x 并尝试了 y 却没有成功?如果是这样,请展示您的尝试,我们可以从那里开始
-
在您执行此服务器端时删除了 javascript 标记。
-
脚本中的 strpos 错误。它是 strpos ( haystack, needle, [position )。
标签: php replace preg-replace href