Question

Given a string in this form:

var myfont = 'Exo 2:600italic';

I need a regex to capture the numeric part of the string after the colon (600) as var1 and any value following the numeric value as var2.

For example, from the above string, I would get:

font-weight:600 //var1 value
font-style:italic //var2 value

Any help, much appreciated.

Was it helpful?

Solution

The following regex should work out for you:

:(?<var1>\d+)(?<var2>\w+)

This uses named groups (i.e. (?<var1> and (?<var2>) so the returned matches, if any, will be accessible via an associative array (with var1 and var2 as the array indexes).

Used with PHP's preg_match():

$input = 'Exo 2:600italic';
$matches = array();
preg_match('/:(?<var1>\d+)(?<var2>\w+)/', $input, $matches);

Output:

print_r($matches);
Array (
    [0] => :600italic
    [var1] => 600
    [1] => 600
    [var2] => italic
    [2] => italic
)

If you want to directly access the values you're after, you can use:

$var1 = $matches['var1'];
$var2 = $matches['var2'];

OTHER TIPS

$myfont = 'Exo 2:600italic';

if (preg_match('~:(\d+)(\w+)~', $myfont, $matches)) {
    print_r($matches);
}

print_r($matches);

Output:

Array
(
    [0] => :600italic
    [1] => 600
    [2] => italic
)

To store the extracted values into new variables, you'd do:

$var1 = $matches[1];
$var2 = $matches[2];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top