separate string in two by given position

Viewed 42847
$string = 'Some string';
$pos = 5;

...??...

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

What is the best way to separate string in two by given position?

8 Answers

Wordwrap works better in my opinion.

$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");
echo $newtext;

The above example will output:

The quick brown fox<br />
jumped over the lazy<br />
dog.

Another example:

$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);

echo "$newtext\n";

The above example will output:

A very
long
wooooooo
ooooord.
<?php
$string = 'Some string';
$pos = 6;
$number_of_pieces = 2;
list($beginning, $end) = split_into_pieces($string, $pos, $number_of_pieces);
// $beginning === 'Some s'; $end === 'tring'

function split_into_pieces($string, $length, $limit = 0) {
  --$length;
  return preg_split("/(?<=^..{{$length}}|(?!^)\\G.{{$length}})/", $text, $limit);
}
  • $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).

<?php
Function Splp($S,...$A){ #Split At Positions 
    $k = 0;
    $R = [];
    $A[] = Strlen($S);
    Foreach($A As $a){
        $R[] = Substr($S,$k,$a-$k);
        $k = $a;
    }
    Return $R;}

$string = 'Some string';
$pos1 = 5;
$pos2 = 7;
[$Start,$Mid,$End] = Splp($string,$pos1,$pos2);
echo $Start,', ',$Mid,', ',$End; #  Some , st, ring
?>
Related