我的 HTML 内容类型为:
<em>this is some</em> dummy text
我想将其格式设置为:(首字母大写,保持 HTML 标签完整)
<em>This is some</em> dummy text
使用 PHP。我不想用
:div:first-letter {
text-transform: uppercase;
}
如果我尝试使用
strip_tags
然后使用 ucfirst
,它无法跟踪 <em>
标签。
function capsfirst_sentence($string) {return empty($string) ? '' : preg_replace('/\b(\w)/e', 'strtoupper("$1")', $string);}
这是在 php 中如果对你有帮助
我敢打赌有更好的方法来实现这一目标。但我认为这个片段可能会有所帮助。它遍历字符串并忽略前缀标签。
<?php
$str = "<foo>string</foo> to loop through";
$strlen = strlen($str);
$inTag = false;
for( $i = 0; $i < $strlen; $i++ ) {
$char = substr( $str, $i, 1 );
if ($inTag) {
if (strcmp($char, ">") == 0) {
$inTag = false;
}
continue;
}
if (strcmp($char, "<") == 0) {
$inTag = true;
continue;
}
substr_replace($str, strtoupper($char), $i, 1);
break;
}
echo($str);
?>
::first-letter 选择器用于向指定选择器的第一个字母添加样式。
注意:以下属性可以与 ::first-letter 一起使用:
text-transform
我认为没有
text-transform
你就无法做到这一点......
所以尝试使用此代码来做到这一点
em {
text-transform:initial;
}
$mystring1 = "<em>this is some</em> dummy text";
$pos1 = stripos($mystring1, '>');
$rest = substr($mystring1, $pos1+1, 1);
$new = ucfirst($rest);
echo substr_replace($mystring1, $new, $pos1+1, 1);
基于@Ненад的回答,因为“”在php中已被废弃,并且正则表达式不会匹配某些情况。
现在使用该功能,您可以发送不同类型的 html 和文本,并且始终会获得第一个真正的字母。
function capsfirst_sentence($string) {
$replaced = preg_replace_callback('/(.*)(>[A-Za-zÀ-ÖØ-öø-ÿ])(.*)/iu',
function ($words) {
return $words[1] . mb_strtoupper($words[2]) . $words[3];
} , $string ,1,$count); // searches for the first ">" + letter and uppercase it.
return empty($string) ? '' : (ucfirst(trim($string)) == trim($string) ? $replaced : ucfirst(trim($string)));
}
示例:
"<p>hello</p>" // returns <p>hello</p>
"<p><strong>hello</strong></p>" // returns <p><strong>hello</strong></p>
"hello" // returns "Hello"
希望对某人有帮助。