I want to pick digits between other groups of digits.
I think it is best that I show this pattern in order to explain what I mean:
xxxxx...xxxxyyyyyyy....yyyyzzzzzzz....zzzz
{ 1000 } { 1500 }
So from the above string structure, I want to pick the digits that occur between the first 1000 digits (xx) and the final 1500 digits (zz).
I tried substr
but as I have to specify the length it didn't work for me. Because I don't know what the length is between those two indexes.
Here is my code:
$id = base64_encode($core->security(1070).$list["user_id"]);
$core->security
creates number as many as what is input. In this it example it creates a length of 1070 random digits.
$decoded = base64_decode($id);
$homework_id = mysqli_real_escape_string($connection,substr($decoded, 1070));
I can pick numbers after some length of digits. But I want to take them between series of digits.
I tried
substr
but as I have to specify the length it didnt work for me. Because I don't the length between 1000 number and 1500 number.
There is a feature of substr
that you might have missed. From the documentation:
If
length
is given and is negative, then that many characters will be omitted from the end of string
So this would work:
$left = 1000; // Number of characters to be chopped off from the left side
$right = 1500; // Number of characters to be chopped off from the right side
$id = substr($id, $left, -$right) ?: "";
The ?: ""
part is there to convert false
to ""
. substr
will return false
when there are not enough characters present in the string to chop off that many characters. If in that case you just want to get an empty string, then ?: ""
will do just that.
You can do it with regex to capture numbers that is between 1000
and 1500
<?php
$number = '10001212121212121500'; #make it string first
if (preg_match('/1000(.*?)1500/', $number, $match) == 1) {
echo (int)$match[1];
}
?>
DEMO1: https://3v4l.org/pebul
DEMO2: https://3v4l.org/8TiWH
$text = <<<HEREDOC
xxxxx...xxxxyyyyyyy....yyyyzzzzzzz....zzzz
{ 1000 } { 1500 }
HEREDOC;
preg_match_all('/\{\s+(\d+)\s+\}/', $text, $matches);
var_dump($matches);
Result:
array(2) {
[0]=>
array(2) {
[0]=>
string(12) "{ 1000 }"
[1]=>
string(15) "{ 1500 }"
}
[1]=>
array(2) {
[0]=>
string(4) "1000"
[1]=>
string(4) "1500"
}
}