Jump to content

preg_match help


asmith

Recommended Posts

Hi,

 

I have a content looks like this:  (it is the  bin2hex() of a file with a space between each)

 

01 68 34 12 0c 0f 02 03 04 43 1f 09 04 32 01 45 29 81 02 03 04 ...

 

I want to get the content starting with 01 and end with 02 03 04. (the red text between bold ones)This phrase may be anywhere in the content and repeating any number.

 

So far I did:

<?php
preg_match_all('/01 (^(02 03 04)+[0-9a-z]{2} )+02 03 04 /', $content, $result, PREG_OFFSET_CAPTURE);
print_r($result);
?>

Link to comment
https://forums.phpfreaks.com/topic/185772-preg_match-help/
Share on other sites

As you'll see, this slightly (not by much, really) complicates things.  The regex below looks for the sets of hex numbers and checks that none of the ones to be captured are "01".  It uses a negative lookbehind assertion to do that (peeking at the last two characters and asserting that they are not "01").  It also captures the space after the last number before "02 03 04", so (to save further complicating the regex) that's why rtrim is applied to the captured values.  It would be possible to not capture that trailing space, at the risk of making the regex more difficult to decipher at-a-glance.

 

$subject = '01 68 34 12 0c 0f 02 03 04 43 1f 09 01 04 32 01 45 29 81 02 03 04 ...';
$pattern = '/01 ((?:[0-9a-f]{2}(?<!01) )+?)02 03 04/';

preg_match_all($pattern, $subject, $matches, PREG_PATTERN_ORDER);
$contents = array_map('rtrim', $matches[1]);

var_dump($contents);

Link to comment
https://forums.phpfreaks.com/topic/185772-preg_match-help/#findComment-981017
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.