Jump to content

breaking down a string by numeric / non-numeric characters


chiprivers

Recommended Posts

Within my current project, I have come across a slight hurdle for which I believe regex is the solution.  I am working with horse racing results and I am currently trying to breakdown a string containing the race length into seperate numeric fields for miles furlongs and yards.  The string is presented int he format:

 

$race_distance = "1m4f100y";

 

Obviously the m, f and y represent miles, furlongs and yards respectively.  I want to end up with three strings like this:

 

$miles = 1;

$furlongs = 4;

$yards = 100;

 

Note however that the numeric figures may be of differeing digit length, not always as the example, and also the string may not include miles, furlongs and yards; it may be:

 

$race_distance = "1m";  which would require: $miles = 1; $furlongs = 0; $yards = 0;

 

Could anybody please help me with a small script that would create these results? Many thanks.

Guest prozente

<pre><?php

$data = '211m43f100y';
preg_match('/(?\d{0,})m)?(?\d{0,})f)?(?\d{0,})y)?/', $data, $matches);

list($all, $miles, $furlongs, $yards) = $matches;

echo 'miles: '.intval($miles)."\n".
     'furlongs: '.intval($furlongs)."\n".
     'yards: '.intval($yards)."\n";

?></pre>

 

EDIT: fixed pattern

Archived

This topic is now archived and is closed to further replies.

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