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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.