php - PHP 文件中的大写链接

标签 php css hyperlink uppercase

仍在学习 PHP 基础知识的路上。 ATM,我正试图找到一种方法来“突出显示”文件中的链接描述。

假设,如果我有类似的东西

 <body>Hello World <a href=http://web.com title="link">This is a link</a>

它会变成

 <body>Hello World <a href=http://web.com title="LINK">THIS IS A LINK</a>

到目前为止,我只成功地使用这段代码替换了一个部分

<?php

$matches = file_get_contents($argv[1]);
preg_match('/=".*a>/', $matches, $links);
print_r($links);
?>

您有什么办法可以将所有这些链接连同它们的标题都大写吗?

最佳答案

不要在 PHP 中这样做。这是一个设计决定,因此应该使用 CSS 完成:

a {
  text-transform: uppercase;
}

如果你真的必须用 PHP 来做,你可以使用 preg_replace_callback() ,它允许您编写自己的函数来处理替换。这可能看起来像这样:

<?php
$string = '<body>Hello World <a href=http://web.com title="link">This is a link</a>';
$string = preg_replace_callback("/(<a.+title=[\"'])(.+?)([\"']>)([^<>]+?)(<\/a>)/", "callback_strtolower", $string);

echo $string;

function callback_strtolower($matches) {
    var_dump($matches);
    return $matches[1] . strtoupper($matches[2]) . $matches[3] . strtoupper($matches[4]) . $matches[5];
}
?>

结果:

<body>Hello World <a href=http://web.com title="LINK">THIS IS A LINK</a>

请注意,此正则表达式并不匹配所有关于如何编写 html 标签的可能性,您将不得不调整它。

另请注意,使用正则表达式修改或解析 HTML 代码通常不是一个好主意。推荐的方法是使用 DOM 解析器:

$dom = new DOMDocument();
$dom->loadHTML($string);
$links = $dom->getElementsByTagName("a");
foreach ($links as $link) {
    foreach ($link->childNodes as $child) {
        if ($child instanceof DOMText)
            $link->replaceChild(new DOMText(strtoupper($child->wholeText)), $child);
    }
    if ($link->hasAttribute("title")) {
        $link->setAttribute("title", strtoupper($link->getAttribute("title")));
    }
}
echo $dom->saveHTML();

关于php - PHP 文件中的大写链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22813656/

相关文章:

php - Javascript - If 条件由 "&&"分隔(需要建议)

PHP 脚本不验证输入

api - 在 REST API 中返回绝对 URI 与相对 URI

html - 从链接的一部分中删除下划线

php - 使用来自 facebook 的 selenium 和 php webdriver 从下拉列表中选择选项

javascript - jQuery 整个页面正在重新加载以更新 css

html - div 中的图像在图像下方有额外的空间

hyperlink - Autohotkey——单击链接、更改链接、启动链接

javascript - jQuery动画后的图像显示问题

javascript - 是否有用于 Ken Burns 效果的 JQuery 插件?