$string = 'Some string'; $pos = 5; ...??... $begging // == 'Some s'; $end // == 'tring';
What is the best way to separate string in two by given position?
split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
You can use substr
to get the two sub-strings:
$str1 = substr($str, 0, $pos); $str2 = substr($str, $pos);
If you omit the third parameter length, substr
takes the rest of the string.
But to get your result you actually need to add one to $pos
:
$string = 'Some string'; $pos = 5; $begin = substr($string, 0, $pos+1); $end = substr($string, $pos+1);
Regex solution (if you are into it):
... $string = 'Some string xxx xxx'; $pos = 5; list($beg, $end) = preg_split('/(?<=.{'.$pos.'})/', $string, 2); echo "$beg - $end";
Regards
rbo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With