I’m trying to write a regular expression that will match the first 8 words of a string (including any punctuation at the end), but I’m running into problems when a word contains an apostrophe or single quote character. My current regex is as follow:
/(\b[\w,']+[.?'!\"]*\s){8}/
and my example string is:
Went for Valentine's day, food was about a B, filet mignon was served chopped up
Currently, The match i’m getting returned is this:
s day, food was about a B, filet
But I want it to be like this:
Went for Valentine's day, food was about a
I tried introudcing a ' into my character set [\w,'] but it’s not working correctly. Any help would be appreciated.
Thanks!
Although this can be done with a regex, this can be done with preg_split at least as easily:
This produces the following output: