Reputation: 323
I have HTML content of type:
<em>this is some</em> dummy text
I want to format it to: (Capitalize first letter keeping the HTML tags intact)
<em>This is some</em> dummy text
using PHP. I don't want to use
:div:first-letter {
text-transform: uppercase;
}
If I try to use strip_tags
and then use ucfirst
, it can't keep track of <em>
tags.
Upvotes: 0
Views: 1132
Reputation: 47900
I don't really know if the input is reliably valid HTML, so I'll offer a regex solution that may not cover all scenarios and uses vague-identification for what constitutes an HTML tag (without creating a massive pattern).
Code: (Demo)
function firstWordToUpper(string $text): string
{
static $consideredWhitespaces = '(?:\s|\x{00A0}| )*';
static $consideredTag = '(?:<[a-z]+[^>]*>)?';
return preg_replace_callback(
"/^(?i:(?:$consideredWhitespaces$consideredTag)*)\K\pl/u",
fn($m) => mb_strtoupper($m[0]),
$text
);
}
echo firstWordToUpper('this is some dummy text');
echo "\n";
echo firstWordToUpper('<em>this is some</em> dummy text');
echo "\n";
echo firstWordToUpper('<div>one</div><p>two</p>');
echo "\n";
echo firstWordToUpper('<p><i>test</i></p>');
Output:
This is some dummy text
<em>This is some</em> dummy text
<div>One</div><p>two</p>
<p><i>Test</i></p>
I've built convenient variables in the function body so that developers can implement their own definition of what is a "non-visible character" and what is an "HTML tag" in this context.
Upvotes: 1
Reputation: 2942
$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);
Upvotes: 0
Reputation: 341
function capsfirst_sentence($string) {return empty($string) ? '' : preg_replace('/\b(\w)/e', 'strtoupper("$1")', $string);}
This is in php If helps you
Upvotes: 1
Reputation: 199
The ::first-letter selector is used to add a style to the first letter of the specified selector.
Note: The following properties can be used with ::first-letter:
text-transform
I think without text-transform
you can not do that.....
so try to do that using this code
em {
text-transform:initial;
}
Upvotes: 0
Reputation: 3638
I'd bet there are better ways to achieve this. But I think this snippet could be of help. It iterates through the string and ignores prefixed tags.
<?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);
?>
Upvotes: 0