20173400157080082
this is my string. I want this string to split in array from 4 to 7 and shows the result like this. Array ( [0] => 400157 )
.I have tried string split but it split from starts of the string. But I want to split string into array by my given character. Thank You
Asked
Active
Viewed 70 times
-2

Marc
- 19,394
- 6
- 47
- 51

Shayan Ishaq
- 47
- 3
-
So the resulting array should always have only 1 element, or why is does the middle part become index 0? Have a look at the [substr()](http://php.net/manual/en/function.substr.php) function. – martinstoeckli Jan 26 '18 at 07:47
-
1Possible duplicate of [Get first n characters of a string](https://stackoverflow.com/questions/3161816/get-first-n-characters-of-a-string) – Ken Y-N Jan 26 '18 at 07:48
-
used this function `$string = substr($string,5,6);` http://sandbox.onlinephpfunctions.com/code/ff8a1a345a5454f2299bc6caa77bedd5d401af43 – Bilal Ahmed Jan 26 '18 at 07:52
-
2Is it always 4 and 7? Sounds odd that you always want number starting with 4 and ending with 7. – Andreas Jan 26 '18 at 08:21
-
@ShayanIshaq can you answer my question above. – Andreas Jan 26 '18 at 10:19
1 Answers
0
Better use substr
and strpos
:
$a = '20173400157080082';
$result = [
substr($a, strpos($a, '4'), strrpos($a, '7') - strpos($a, '4') + 1);
];
Or you can use preg_match_all
, but this uses more resources:
$a = '20173400157080082';
preg_match_all('/[4](.*)+[7]/', $a, $match);
$result = $match[0];

Vladimir
- 1,373
- 8
- 12
-
@Shayan Ishaq ~ You should mark as correct if this solved the problem – Professor Abronsius Jan 26 '18 at 07:58
-
1
-
-
Reversed you anwer. You should never use regex when simple string functions suffice. – Martijn Jan 26 '18 at 08:37
-
thanks and what should I do when i want to break array not string $a = array('20173400157080082'); – Shayan Ishaq Jan 26 '18 at 09:32
-
-
-