使用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("