php标题文字颜色h2,使用PHP将大写的H1,H2,...标签转换成大写字母(Turn uppercase H1, H2,… tags into capitalized title with PHP...

使用PHP将大写的H1,H2,...标签转换成大写字母(Turn uppercase H1, H2,… tags into capitalized title with PHP)

我想用PHP将大写的h1,h2,...标签变成大写的文本。 我很近,但还没有。 下面的代码片段不会将“LOREM”的第一个字符转换为大写(可能是因为它会尝试大写'

$var = "

LOREM IPSUM DOLORES AMET

THIS IS SOME TEXT

LOREM IPSUM DOLORES AMET

";

$line = preg_replace_callback(

'/(.*)\>/i',

function ($matches) {

return ucfirst(strtolower($matches[0]));

},

$var

);

print($line);

结果是:

lorem ipsum dolores amet

THIS IS SOME TEXT

lorem ipsum dolores amet

期望的输出:

Lorem ipsum dolores amet

THIS IS SOME TEXT

Lorem ipsum dolores amet

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 '

$var = "

LOREM IPSUM DOLORES AMET

THIS IS SOME TEXT

LOREM IPSUM DOLORES AMET

";

$line = preg_replace_callback(

'/(.*)\>/i',

function ($matches) {

return ucfirst(strtolower($matches[0]));

},

$var

);

print($line);

Results in:

lorem ipsum dolores amet

THIS IS SOME TEXT

lorem ipsum dolores amet

Desired output:

Lorem ipsum dolores amet

THIS IS SOME TEXT

Lorem ipsum dolores amet

原文:https://stackoverflow.com/questions/28036731

更新时间:2020-01-14 12:14

最满意答案

使用DOMDocument

$var = "

LOREM IPSUM DOLORES AMET

THIS IS SOME TEXT

LOREM IPSUM DOLORES AMET

";

$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("

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值