I need to use the excerpt() function to set a text preview of a blog post. But in my client’s use-case, they usually starts off the blog post by adding inline images and a header right after.
When the excerpt() function finds something like this (image: file.jpg caption: text), the outcome is that the text after caption: is printed, together with the header and the rest of the text.
Would making a pre-hook kirbytext filter be the way to go to strip out both the image caption and h3 tag?
Indeed I thought about point 2 as well, which would just be more easier for them and less maintenance problems in the future.
Though I was thinking that if I’d go with a kirbytext filter, probably using a post hook let me easily catch the first <figure> and any of <h1> etc in the html output.
kirbytext::$post[] = function($kirbytext, $text) {
// 1. catch first-only instance of <figure> and any of <h1-h6>
$match = '!(<figure(.*))|(<*.(h1|h2|h3|h4|h5|h6).*>)!is';
$text = preg_replace_callback($match, '', $kirbytext, 1);
return $text;
which is throwing an error because argument 2 is not valid (→ ''). I am not following the kirby column example of looping through every instance of the matched result, because I only need to match the first instance of the regex (so I put 1 a the end of the preg_replace_callback).
Come to think about it, a filter is not really that useful, because it will always be applied. You don’t want that. Its probably better to replace kirbytext first and then get an excerpt.
<?php
// an optional figure tag followed by optional line breaks and optional headers
$pattern = '!(<figure.*<\/figure>)?(\n*)?(<h[1-6].*<\/h[1-6]>)?!is';
// lets fetch some text from the starter kit with an image and h3
$kirbytext = page('projects/project-a')->text()->kirbytext();
$result = preg_replace($pattern, '', $kirbytext);
echo excerpt($result);