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.

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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