L. van Arkel
L. van Arkel

Reputation: 1

Analysing string in php

For a project, I have an input, which consists of numbers and letters, in a specific order, send from another web page. E.g. 7 numbers for an ID, a number followed by 2 letters for groups, and 1, 2, or 3 numbers for a room number. To seperate them, I think I have to iterate through the whole string, see for each char if it is a number or a letter, and then use a lot of if/then functions to get the correct type. Is there a better way to do this, or is this a good way to do it.

Upvotes: 0

Views: 64

Answers (1)

Romain Canon
Romain Canon

Reputation: 21

Using a regular expression should be the best solution here, as it would both tell you if the ID does match the wanted syntax, as well as getting the several parts of this ID in an array.

For the example you gave:

$idList = [
    '1AB12', // OK
    '1AB123', // OK
    '1AB1234', // KO
    'AB1234', //KO
    '12AB12', //KO
];

foreach ($idList as $id) {
    $isOk = preg_match('/^([0-9])([a-zA-Z]{2})([0-9]{1,3})$/', $id, $match);

    if ($isOk) {
        echo 'OK : ' . $id;
        var_dump($match);
    } else {
        echo 'KO : ' . $id;
    }
}

Upvotes: 1

Related Questions