1

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 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thx Wiktor. I edited my question. Wit both of your proposals I have the same problem.
With preg_match('/^.{8}\K.*(?=.{13}$)/', $a, $matches); this works, again with the 13
@hamburger That is not related to regex. Anyway, I get "Fatal error: Uncaught Error: Undefined constant "RT" in /tmp/preview:6" error when trying your code.
RT is deleted, it is only a linefeed
@hamburger I get 500, see this PHP demo.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.