-1

I have a string like this: $str="moolti1" and I want this to be cut into two strings or something like that. I need "m00lti" and "1". As the first part is always the same length (6), isn't there a method like $pre=$str[0:5]?

Alireza Fallah
  • 4,609
  • 3
  • 31
  • 57
vossmalte
  • 174
  • 2
  • 2
  • 16
  • 7
    You mean you couldn't find [substr()](http://www.php.net/manual/en/function.substr.php) in the PHP docs? – Mark Baker Jan 24 '14 at 17:18
  • I think @m00lti wants the method to return both parts, not just one substring – i-bob Jan 24 '14 at 17:22
  • 1
    If it's both parts in a one-liner because using `substr()` twice is too hard; then `list($firstPart, $secondPart) = str_slit($str, 6);` – Mark Baker Jan 24 '14 at 17:23
  • @MarkBaker That will fail for strings of length >= 13. – Amber Jan 24 '14 at 17:24
  • @Amber - then let Moolti use 2 substrings..... I've got better things to do with my time than provide answers to cover every single possible circumstance for something that's as basic as `substr()`. OP gives no indication that his strings will be longer than 13 characters; and the subject line of the question suggests otherwise – Mark Baker Jan 24 '14 at 17:25
  • @MarkBaker I wasn't saying you should keep providing answers; I was just saying that your original comment was the better one. :) – Amber Jan 24 '14 at 17:42

3 Answers3

2
$str="moolti1";

$start = substr($str, 0, 6);

$end = substr($str, 6);

You may find I have a number out somewhere as I always ALWAYs get confuzzled with my start indexes and lengths but this should give you what you need.

GrahamTheDev
  • 22,724
  • 2
  • 32
  • 64
  • The `strlen($str) - 1` part is unnecessary; `substr()` automatically goes until the end of the string if the length argument is omitted. – Amber Jan 24 '14 at 17:23
  • good point - its my vb.net habits that always come into php - will ammend and thanks for catch – GrahamTheDev Jan 24 '14 at 17:24
2
$str="moolti1";

$parts = str_split($str, 6);
MattDMo
  • 100,794
  • 21
  • 241
  • 231
Jonny White
  • 875
  • 10
  • 21
  • Great answer if end part is never more than 6 characters - with string moolti143243342343242 you would get 3 parts but if you know the end part won't be greater than 6 characters then this is best answer! I have +1 this as it is elegant solution if suitable – GrahamTheDev Jan 24 '14 at 17:27
  • thanks! i just didn't know the `list()` function, thanks to @MarkBaker for the comment on my post! – vossmalte Jan 24 '14 at 17:33
1

Use PHP's substr() function

$str = 'moolti1';
$first_five = substr($str, 0, 5);
$last_two = substr($str, -2);

More info here

Lance
  • 4,736
  • 16
  • 53
  • 90