Home > front end >  PHP preg_match for getting a string out with variable length
PHP preg_match for getting a string out with variable length

Time:01-13

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

CodePudding user response:

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

CodePudding user response:

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

  • Related