phpregexcapitalizationucfirst

PHP - apply ucfirst() to first character that isn't HTML


I'm outputting a string assembled from a few different parts, and some of those parts may or may not contain some HTML. If I apply ucfirst() to the string and there's HTML before the text to be displayed then the text doesn't get proper capitalization.

$output = $before_text . $text . $after_text;

So if I've got

$before_text = 'this is the lead into ';
$text = 'the rest of the sentence';
$after_text = '.';

then ucfirst() works fine and $output will be

This is the lead in to the rest of the sentence.

But this

$before_text = '<p>';
$text = '<a href="#">the sentence</a>.';
$after_text = '</p>';

won't do anything. So I guess I need a function or regex to make its way to the first actual, regular text and then capitalize it. But I can't figure it out.


Solution

    1. use strip_tags in $text and save in $temp: this should give you text that is not html.
    2. apply ucfirst on $temp and call it $temp_ucfirst: this should give you string upper-cased.
    3. use str_replace to replace $temp in $text with $temp_ucfirst: this should replace the not-html text with the upper-cased one.