Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

separate string in two by given position

Tags:

$string = 'Some string'; $pos = 5;  ...??...  $begging // == 'Some s'; $end // == 'tring'; 

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

like image 997
Qiao Avatar asked Aug 10 '10 13:08

Qiao


People also ask

How do you split a string into parts based on a delimiter?

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.

What is split () function in string?

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.


2 Answers

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); 
like image 81
Gumbo Avatar answered Oct 21 '22 20:10

Gumbo


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

like image 27
rubber boots Avatar answered Oct 21 '22 20:10

rubber boots