2

I have to convert many, many known MAC strings (always 12 chars) via PHP in order to loop and lookup in tickets content if they exist in any of the three form.

They come at this format from our db : A0B0C0D0E0F0 (12 chars always).

I need some code to turn them into both A0:B0:C0:D0:E0:F0 and then A0-B0-C0-D0-E0-F0.

code would do something like

while ($row = mysqli_fetch_object($resultmac) {

    if (strpos($ticket, $row->mac) !== false || strpos($ticket, //mac with ":"//) !== false || strpos($ticket, //mac with "-"//) !== false) {
        echo "found match : ";
    }

}

(I use "!== false" because i read here that it was a good way to do it)

Is there a better way then converting the string to an array and manually add ":" or "-" after each sets of two chars?

Community
  • 1
  • 1
Quardah
  • 183
  • 1
  • 4
  • 14
  • 1
    So what is the question now? How to get `A0B0C0D0E0F0` into `A0:B0:C0:D0:E0:F0` and `A0-B0-C0-D0-E0-F0` ? – Rizier123 Feb 18 '15 at 14:37
  • You can use regular expressions to match/replace the chars in mac addresses. If you are worried about the performance you should create a small benchmark to compare the options. – Filipe Borges Feb 18 '15 at 14:38
  • lol sorry you are right i forgot to mentionned clearly the question. Indeed the goal was to convert the mac address. – Quardah Feb 18 '15 at 15:03
  • @Quardah FYI: you can use `@name` so that this person get's a notification :D (just added another solution what should work for you) – Rizier123 Feb 18 '15 at 15:10
  • Thanks! It works as well. Now my only concern is which way is the best performance-wise, because this will most probably be applied to our production db (which contains about 3 millions entry :/). – Quardah Feb 18 '15 at 16:35

2 Answers2

2

You can get the string to an array quickly with:

$mac = 'A0B0C0D0E0F0';
$bytes = str_split($mac, 2);

The array $bytes now has each of the hex numbers. You can then:

$colons = implode(':', $bytes); // A0:B0:C0:D0:E0:F0
$dashes = implode('-', $bytes); // A0-B0-C0-D0-E0-F0
  • That is a magnificient work of art. It is/does exactly what i expected. Many thanks for the fast response and have a nice day! – Quardah Feb 18 '15 at 15:03
2

This should work for you:

(Here i just use wordwrap())

<?php

    $str = "A0B0C0D0E0F0";

    echo wordwrap($str, 2, ":", TRUE);
    echo wordwrap($str, 2, "-", TRUE);

?>

Output:

A0:B0:C0:D0:E0:F0
A0-B0-C0-D0-E0-F0
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • Hey this is cool too i didn't know about the wordwrap function. I'll give it a try thanks for the tip!! – Quardah Feb 18 '15 at 16:34