1

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.

nickfindley
  • 308
  • 1
  • 9
  • 1
    Have you considered using css? It's much more easier and efficient that way, IMO. text-transform: uppercase; – Smoking Sheriff Feb 20 '18 at 02:56
  • 1
    Is $text always max 1 html tag or it can be more? – Francesco Meli Feb 20 '18 at 02:58
  • Do you have control over the string of HTML you're assembling, or no? If you do, you should be able to add logic quite easily to ensure your text has `ucfirst()` applied. – 1000Nettles Feb 20 '18 at 03:07
  • @pnknrg the $before_text, $text, and $after_text can be pretty much anything. Whether or not that's a bad idea is a different discussion. – nickfindley Feb 20 '18 at 03:10
  • @1000Nettles there's no telling what could be in there. – nickfindley Feb 20 '18 at 03:11
  • Please provide more test cases: `what is it?`, `what is it?`, etc. – bishop Feb 20 '18 at 03:15
  • @SmokingSheriff good idea, so I just tried it. In this particular case the first item is an SVG icon, which apparently counts as ::first-letter. – nickfindley Feb 20 '18 at 03:16
  • For anyone looking for something similar: _do not try parsing HTML with regex_ : https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – 1000Nettles Feb 20 '18 at 03:21

1 Answers1

3
  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.
Francesco Meli
  • 2,484
  • 2
  • 21
  • 52