dpyoh6553 2019-02-16 08:41
浏览 36
已采纳

选择字符串内特定部分的数字

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.

  • 写回答

3条回答 默认 最新

  • doqrt26664 2019-02-16 09:10
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?