PHP String parsing / regex
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need a function to parse strings like FOO/1.1.1.BAR.md

Into three parts:

$part1 = 'FOO' and
$part2 = '1.1.1' and
$part3 = 'BAR.md'

Part1 will only ever contain letters

Part2 will always follow some integer.integer.integer pattern, and the integers may be one or more digits long.

Part3 will only ever contain some letters followed by the .md extension.

Include a check for if the given string does not follow the above rules, i.e. it's not parsable.

awarded to weslly
Tags
PHP
regex
parse

Crowdsource coding tasks.

1 Solution

Winning solution

Here's it:

<?php
$test_string = "FOO/1.1.1.BAR.md";
preg_match("/^([A-z]+)\/(\d+\.\d+\.\d+)\.([A-z]+\.md)$/i", $test_string, $result);

if (!empty($result)) {
    print_r($result);
    $part1 = $result[1];
    $part2 = $result[2];
    $part3 = $result[3];
}

/*
Array
(
    [0] => FOO/1.1.1.BAR.md
    [1] => FOO
    [2] => 1.1.1
    [3] => BAR.md
)
*/
?>