Jump to content

working with a string..


Michdd

Recommended Posts

I need something that will process a string accordingly:

 

I have a string that will change, but always be in this format (example):

 

324,3;65,6;93,10; etc..

 

First number, second number; repeat..

 

I need something that will split that up into an array first (obviously) and check if the first number in any of those sets is a 0, if it is a 0, then remove that whole set from the array, then turn it back into a string.

 

Might be hard to understand so here's an example:

 

324,3;65,6;0,17;93,10;

 

would be turned into: 324,3;65,6;93,10;

The set (0,17;) was removed because the first number is 0.

Link to comment
Share on other sites

function removeZeroRecords($string)
{
    //Separate the string into an array on semicolon
    $records = explode(';', $string);

    //Iterate through each record in the array
    foreach ($records as $index => $record)
    {
        //Separate record into the first/second numbers based on comma
        $parts = explode(',', $record);
        if ($parts[0]=='0')
        {
            //Remove records that have a 0 as starting number
            unset($records[$index]);
        }
    }
    //Combine the remaining records into a strin and return it
    return implode(';', $records);
}

$string = "324,3;65,6;0,17;93,10;";
echo removeZeroRecords($string);

//Output: 324,3;65,6;93,10;

Link to comment
Share on other sites

Or, you can do it with a regular expression

 

function removeZeroRecords($string)
{
    $string = ';'.$string;
    $string = preg_replace('/;0,[^;]*/', '', $string);
    return substr($string, 1);
}

$string = "324,3;65,6;0,17;93,10;";
echo removeZeroRecords($string);

//Output: 324,3;65,6;93,10;

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.