php - 仅更改部分页面的基本 URL

标签 php html url symfony relative-path

我的站点上有一个页面可以从同一服务器上另一个(遗留)站点的数据库中获取并显示新闻项目。一些项目包含相对链接,应予以修复,以便它们指向外部站点,而不是在主站点上导致 404 错误。

我首先考虑使用 <base>在获取的新闻项上添加标签,但这会更改整个页面的基本 URL,破坏主导航中的相关链接 - 而且感觉也很糟糕。

我目前正在考虑创建一个正则表达式来查找相对 URL(它们都以 /index.php? 开头)并在它们前面加上所需的基本 URL。有没有更优雅的解决方案?该站点基于 Symfony 2 构建并使用 jQuery。

最佳答案

下面是我将如何解决这个问题:

function prepend_url ($prefix, $path) {
    // Prepend $prefix to $path if $path is not a full URL
    $parts = parse_url($path);
    return empty($parts['scheme']) ? rtrim($prefix, '/').'/'.ltrim($path, '/') : $path;
}

// The URL scheme and domain name of the other site
$otherDomain = 'http://othersite.tld';

// Create a DOM object
$dom = new DOMDocument('1.0');
$dom->loadHTML($inHtml); // $inHtml is an HTML string obtained from the database

// Create an XPath object
$xpath = new DOMXPath($dom);

// Find candidate nodes
$nodesToInspect = $xpath->query('//*[@src or @href]');

// Loop candidate nodes and update attributes
foreach ($nodesToInspect as $node) {
    if ($node->hasAttribute('src')) {
        $node->setAttribute('src', prepend_url($otherDomain, $node->getAttribute('src')));
    }
    if ($node->hasAttribute('href')) {
        $node->setAttribute('href', prepend_url($otherDomain, $node->getAttribute('href')));
    }
}

// Find all nodes to export
$nodesToExport = $xpath->query('/html/body/*');

// Iterate and stringify them
$outHtml = '';
foreach ($nodesToExport as $node) {
    $outHtml .= $node->C14N();
}

// $outHtml now contains the "fixed" HTML as a string

See it working

关于php - 仅更改部分页面的基本 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11759028/

相关文章:

php - Concat 在 Eloquent 更新

php - 字符串运算,如二进制 AND

javascript - 如何从字符串、html输入提交中提取期望值

javascript - 使用 jQuery 使 html5 音频片段在悬停时产生共鸣

java - 如何检测和删除 URL 中的一句话?

r - 避免在 R 中进行 url 编码

php - 使用 php/mysql/jQuery 随机聊天

带有间隔列名称别名的 php 查询字符串

javascript - Bootstrap 5 - 页面加载时模式打开

java - 在 Struts 2 操作名称中使用破折号