douxian6086 2014-04-02 13:52
浏览 82

PHP中的文件中的大写链接

Still on my way to learn PHP basics. ATM, I'm trying to find a way to "highlight" links description in a file.

let's say, if I got something like

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

it would turn into

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

This far, I only managed to replace a single part by using this code

<?php

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

Do you see any way to uppercase all these links, along with their titles ?

  • 写回答

2条回答 默认 最新

  • drll85318 2014-04-02 13:54
    关注

    Don't do this in PHP. This is a design decision, so it should be done with CSS:

    a {
      text-transform: uppercase;
    }
    

    If you really have to do it in PHP, you can use preg_replace_callback(), which allows you to write your own function that handles the replacement. This could look like this:

    <?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];
    }
    ?>
    

    Result:

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

    Note that this regular expression doesn't match all possibilities on how to write the html tags, you will have to adapt it.

    Also note that it is usually a bad idea to use regular expressions to modify or parse HTML code. The recommended way is to use a DOM parser:

    $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();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题