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
https://forums.phpfreaks.com/topic/150213-working-with-a-string/
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;

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;

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.