0

From the research I've done this seems to be a very difficult problem, but I'm wondering if anyone has a code snippet they've come up with that does the job.

I have a number of paragraphs that have dashes, colons or periods. I want to bold the text up until the first punctuation mark of this type. For example,

Paragraph 1: Total precipitation is increasing, primarily as rain. Between 1901 and 2014, total annual precipitation increased by 7% in the northeastern U.S.

Paragraph 2: Frozen ground conditions are more variable and often less frequent: Temperatures are rising, with the greatest increases occurring during the winter season.

Paragraph 3: Earlier spring thaws - some more text describing this situation.

I tried splitting the string on any punctuation into an array, but then I lose the punctuation in the paragraph when I implode again.

Here is the code I tried:

<?php
$s='Frozen ground conditions are more variable and often less frequent: Temperatures are rising, with the greatest increases occurring during the winter season. ';
$sentences=preg_split('/\s*[,:;!?.-]\s*/u', $s, -1, PREG_SPLIT_NO_EMPTY);
?>
<span class="bold"><?php echo $sentences[0]; ?></span><?php echo implode(array_shift($sentences)); ?>

I also tried using the css ::first-line, but that bolds more text than I want.

Is there a good way to go about this?

xanabobana
  • 63
  • 2
  • 16
  • You 'tried', but you do not show code ? – Luuk Feb 28 '21 at 14:25
  • Reference: https://www.php.net/manual/en/function.preg-replace.php – Joe Ward Feb 28 '21 at 14:40
  • Please provide [mre], and not some code which produces: `Fatal error: Uncaught TypeError: implode(): Argument #1 ($pieces) must be of type array, string given` – Luuk Feb 28 '21 at 14:59
  • Thanks! @JoeWard. When I try to use that expression (with a closing ' in the first argument that seems missing) I get an error that 1, 2 and 3 are not defined? – xanabobana Feb 28 '21 at 14:59
  • I was able to use my test code and this question to figure it out https://stackoverflow.com/questions/11758465/how-do-i-include-the-split-delimiter-in-results-for-preg-split – xanabobana Feb 28 '21 at 15:38
  • Apologies. Deleting previous. Replacing with: $para = preg_replace('/(^.+?\:)([\s\w,]+)(.+)/', "$1$2$3", $para); – Joe Ward Feb 28 '21 at 19:03

0 Answers0