简体   繁体   中英

PHP Regex match full stop after certain number of characters

I can't figure out how to do this with regex. I want to match a full stop after a certain number of characters in the sentence.

this is a long sentence. it contains a few full stops in it. I want to match the full stop after the halfway point.

this sentence is shorter. it also contains full stops but not many.

It should not match the last full stop either. It should match the second full stop in the first sentence and have no match in the second. So the match should look like this:

this is a long sentence. it contains a few full stops in it[.] I want to match the full stop after the halfway point.

this sentence is shorter. it also contains full stops but not many.   [no match]

Is there a way to do it? I have something along the lines of this which doesn't work at all:

/[.]{20,}/

As per your feedback ,

.{30,}?\K\.(?=.{30,})

pattern works for you. See the regex demo .

The idea is to find the line length, divide by 2 to get the char at the middle, and subtract 1 or 2 from the value obtained and use it in place of 30 in the limiting quantifier in the pattern above.

Pattern details

  • .{30,}? - any 30 chars other than line break chars or more, but as few as possible,
  • \\K - match reset operator that omits the text matched so far
  • \\. - a dot
  • (?=.{30,}) - a positive lookahead that requires the presence of at least 30 any chars other than line breaks immediately to the right of the current location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM