0

Suppose I have a post and it's the first paragraph is:

"This a Pen. The color is red."

I want to add a custom text like "2022" after "Pen" on first sentence, at the end of the text line.

Example: "This a Pen, 2022. The color is red."

I need to add this to all of the posts automatically. Is there a way to do that? Or do I have to replace in the database?

1 Answer 1

1

You can use a regular expression to sniff for it on the the_content filter.

add_filter( 'the_content', 'wpse403518_custom_text' );
function wpse403518_custom_text( $content ) {
    $regex   = '/^([^\.!?]+)([\.!?])(.*)$/';
    $replace = '$1 2022$2$3';
    $content = preg_replace( $regex, $replace, $content );
    return $content;
}

The regex

The $regex variable is a regular expression, and what it does, roughly, is this:

  • ^ means the start of the string; then
  • ([^\.!?]+) means "match everything that is not a ., !, or ? one or more times" (ie, the first sentence, until we hit a ., !, or ?); then
  • ([\.!?]) means "match a single ., !, or ?" (ie, the first sentence-ending punctuation in the string); then
  • (.*) means "all the characters"; then
  • $ means "the end of the string".

The $replace variable assigns $1 to the first group above (the first sentence), $2 to the second group (ie, the first ., !, or ?), and $3 to the third group (ie, the rest of the content). So what happens is that the 2022 gets inserted between the first sentence and the punctuation at its end, then the rest of the text gets printed as normal.

References

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.