skip to Main Content

I have the following string example: 034a412f500535454e5
Here I would get the 500 out.
The search-string has always 8 digits in front and 8 digits behind. The "500" can have a different lenght of digits (p.ex. 12345).

With a lot of trial end error I found that

preg_match('/(.{8})(.*)(.{13})/', $a, $matches); 

It works. But I tink that not the way it is.

I do not understand why the left side has {8} and the right is {13}.

I get my String at following:

$lastInsertedId = 500;
$numArray = str_split(bin2hex(random_bytes(8)), 8);
$newArray = [$numArray[0],$lastInsertedId,$numArray[1]]; 
$a = vsprintf('%s%s%s',$newArray); 

by using:

preg_match('/^.{8}K.*(?=.{8}$)/', $a, $matches);

the result is 50053545. It will not gives the right value back.

by using:

preg_match('/^.{8}K.*(?=.{8}$)/', '034a412f500535454e5', $matches);

it gives 500 back

Whats wrong?

gettype($a) gives string back.
I’am on php 8.1.13

2

Answers


  1. Chosen as BEST ANSWER

    vsprintf gives a wrong number of digits back. strlen('034a412f500535454e5') gives 19 strlen($a) gives 25. I'am using sprintf instead.


  2. If you want to do that with a regex, you can use

    ^.{8}K.*(?=.{8}$)
    

    See the regex demo. Use the s flag if the string contains line breaks.

    Details

    • ^ – start of string
    • .{8} – eight chars
    • K – omit what was matched so far
    • .* – any zero or more chars
    • (?=.{8}$) – a positive lookahead that requires any eight chars followed by the end of string location to appear immediately to the right of the current location.

    Also, consider using substr:

    $text = '034a412f500535454e5';
    echo substr($text, 8, strlen($text)-16); // => 500
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search