2

I have a string like this

4-1,4-1,,,1-1,,5-4,2-1,

and I need to extract the first number in each pair. For example, (4 -1, 4 -1,,, 1 - 1,, 5 - 4, 2 -1 ,)

Does anyone know how I could achieve this?

2 Answers 2

1
$string = '4-1,4-1,,,1-1,,5-4,2-1,';

preg_match_all('/(\d+)-/', $string, $matches);
// search for 1 or more digits that are followed by a hyphen, and return all matches

print_r($matches[1]);

Outputs:

Array
(
    [0] => 4
    [1] => 4
    [2] => 1
    [3] => 5
    [4] => 2
)
Sign up to request clarification or add additional context in comments.

1 Comment

Think I'll accept this answer as it's less code. Thank you both
1
$couples = explode(",", $data);
$values = Array();

foreach ($couples as $couple)
{
    if ($couple != "")
    {
        $split = explode("-", $couple);
        $values[] = $split[0];
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.