separate string in two by given position

前端 未结 8 1109
萌比男神i
萌比男神i 2020-12-03 17:14
$string = \'Some string\';
$pos = 5;

...??...

$begging // == \'Some s\';
$end // == \'tring\';

What is the best way to separate string in two by

8条回答
  •  盖世英雄少女心
    2020-12-03 18:03

    • $string is the string to split
    • $length is the size of each piece in Unicode code-points (or ASCII characters if not using the UTF-8 option, see below). Any value less than 1 will return the entire input string as a single piece
    • $limit is the maximum number or pieces, or 0 for unlimited. The final piece will contain the remainder of the string and might be longer or shorter than $length

    The regex that is doing the magic is using a positive look-behind (?<= ... ). It looks for ^, which is the start of the string, | or if it's not at the beginning of the string (?!^) it looks for \G, which is the position of the previous match. . is any character, { n } is repeated n times, where n is {$length}. When using \G, it adds an extra character for some reason, which is why there's the line --$length; and why the first match has an extra . to search for an extra code-point, which is not usually allowed in look-behinds. I think the zero-width assertions ^ and \G are anchoring the pattern, allowing different lengths in the look-behind.

    The extra { and } around $length are necessary to stop the regex braces being interpreted as an escaped PHP variable. /su are the regex options. The /s option says allow . to match newline characters. The /u option says to match Unicode code-points encoded as UTF-8 (remove u if you are parsing strings that are non-UTF-8 compliant).

提交回复
热议问题