views:

56

answers:

4
$string = 'Some string';
$pos = 5;

...??...

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

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

+1  A: 

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

If i understand you correctly, you can do:

$str = 'hello world';
$pos = 5;

$separated_str = substr($str, $pos);
echo $separated_str;

Result:

world

This depends on the structure of your string as there are other ways also to split the string.

Sarfraz
+4  A: 

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($str, 0, $pos+1);
$end = substr($str, $pos+1);
Gumbo
Beware when dealing with multibyte strings!
Török Gábor
By using `$pos+1` you're omitting a character. Given a $pos of 5, you'll wind up with `"Some "` and `"tring"`
meagar
@meagar: Whoops, thanks for the remark!
Gumbo
-1, too verbose.
stereofrog
@Gumbo My first instinct was to add a similar comment on Tim's answer telling him he was doing it wrong by *not* using `$pos+1` :) +1 for the fixed-up answer at any rate
meagar
@meagar: My primary intention is to have correct answers.
Gumbo
+2  A: 

How about substr()?

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

$beginning = substr($string, 0, $pos);
$end = substr($string, $pos);
Tim Chaves
A: 

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

rubber boots
Such an inappropriate use of regular expressions...
meagar
Ohh, I see, if i respond to a PHP question and **do not** repeat the obvious solution (which was given identically four times so far) and try to show an alternative, I'll be downvoted by the peers. Nice!
rubber boots
+1, good answer
stereofrog
@rubber boots: convince people of the advantage of your solution over the `substr` way.
Török Gábor
There is only one way to settle this... Quick! Someone do a benchmark performance test and compare the results!
iandisme