1

Hi what is the best was to split a paragraph into sentences please?

I can use:

{{ content|split('.') }}

but what if a sentence in the paragraph ends with a question mark or exclamation mark instead? Such as:

This is a sentence. This is also a sentence that really interests me! Why shouldn't this be classed as a sentence? This is also a sentence.

How can I easily split that string into an array of 4 like this:

[0] This is a sentence
[1] This is also a sentence that really interests me
[2] Why shouldn't this be classed as a sentence 
[3] This is also a sentence

In php you can use:

$content = preg_split( "/(\?|\.|!)/", $content ); 

But this doesn't work with twig.

Also just to make it a bit harder, I would like the strings to keep the characters that are used as delimiters:

[0] This is a sentence. 
[1] This is also a sentence that really interests me! 
[2] Why shouldn't this be classed as a sentence? 
[3] This is also a sentence.

Any help would be much appreciated. Thanks

1

If you're happy relying on a plugin then the Expressive plugin adds the preg_split function e.g {{ content|preg_split("/(\?|\.|!)/") }}

2

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.