dtrotfd1012 2015-01-20 02:18
浏览 100
已采纳

使用PHP将大写的H1,H2,...标记转换为大写标题

I would like to turn uppercase h1, h2,... tags into capitalized text with PHP. I'm close, but not there yet. The below snippet does not turn the first character of "LOREM" into uppercase (probably because it tries to uppercase '<'). It would be easy to modify the callback PHP function, but I wish I could do this by only modifying the regex piece:

$var = "
<h1>LOREM IPSUM DOLORES AMET</h1>
THIS IS SOME TEXT
<H2>LOREM IPSUM DOLORES AMET</H2>";

$line = preg_replace_callback(
    '/<h[1-9]>(.*)\>/i',
    function ($matches) {
        return ucfirst(strtolower($matches[0]));
    },
    $var
);

print($line);

Results in:

<h1>lorem ipsum dolores amet</h1>
THIS IS SOME TEXT
<H2>lorem ipsum dolores amet</H2>

Desired output:

<h1>Lorem ipsum dolores amet</h1>
THIS IS SOME TEXT
<H2>Lorem ipsum dolores amet</H2>
  • 写回答

4条回答 默认 最新

  • dongli8862 2015-01-20 03:11
    关注

    Use a DOMDocument

    <?php
    
            $var = "
    <h1>LOREM IPSUM DOLORES AMET</h1>
    THIS IS SOME TEXT
    <H2>LOREM IPSUM DOLORES AMET</H2>";
    
            $dom = new DOMDocument();
            $dom->loadHTML($var);
    
            $tags = array("h1", "h2");
            //loop thru all h1 and h2 tags
    
            foreach ($tags as $tag) {
                //get all elements of the current tag
                $elements = $dom->getElementsByTagName($tag);
                //if we found at least 1 element
                if (!empty($elements)) {
                    //loop thru each element of the given tag
                    foreach ($elements as $element) {
                        //run ucfirst on the nodevalue
                        //which is equivalent to the "textContent" property of a DOM node
                    $element->nodeValue = ucfirst(strtolower($element->nodeValue));
                    }
                }
            }
    
    $html = $dom->saveHTML();
    //remove extra markup
    $html = str_replace("</body></html>","",substr($html,strpos($html,"<h1>"));
    echo $html;
    
    <h1>Lorem ipsum dolores amet</h1>
    THIS IS SOME TEXT
    <h2>Lorem ipsum dolores amet</h2>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据