Split the string after some characters with preg_match

I found this code that will contain no more than 300 characters, and then break in the next closest break word:

 $var = 'This is a test text 1234567890 test check12.' # 44 chars
 preg_match('/^.{0,300}(?:.*?)\b/iu', $var, $matches);
 echo $matches[0];

44 is less than 300, so I expect the result to be the same as $ var.

But the way out:

 This is a test text 1234567890 test check12   # 43 chars

$ matches [0] doesn't give me a dot at the end, however $ var does. Can anyone tell me how to get the complete line (with dot)?

+3
source share
4 answers

I could get the expected result:

  • Delete \b
  • Replacement \bfor$

EDIT:

, . .* \b, , .

, , . .

+2

preg_match 300 . :

substr($var, 0, strpos($var, ' ', 300));

300 , .

+2
'/^.{300}(?:.*?)\b|^.*{0,300}/u'

, . - , .

+1

(?:. *?)

* . , , . , , .

,

 preg_match('/^(.){0,300}\b/iu', $var, $matches);
0
source

Source: https://habr.com/ru/post/1734244/


All Articles