2

I use preg_match_all($pattern, $string, $matches) regularly on data, and basically, I always need to remove either £0.00 or $0.00 or €0.00 from the array should it be in there.

I never know the position within the array that it will be in, if at all.

I've tried unset($matches['£0.00']) and unset($matches[0]['£0.00']) but didn't work

Also, can it be done without using the actual currency symbol and maybe regex \p{Sc}

So, summary, I have an array of numbers with currency symbols, and need to remove any zero entries.

sample array:

Array ( [0] => Array ( [0] => £18.99 [1] => £0.00 [2] => £0.00 [3] => £0.00 ) ) 

Is this possible?

4
  • can you show us sample array structure? Commented Nov 19, 2012 at 6:06
  • @MuthuKumaran - hi, added sample Commented Nov 19, 2012 at 6:08
  • Why don't you modify your $pattern to not match those in the first place? Commented Nov 19, 2012 at 6:31
  • What is the expected result? Commented Nov 19, 2012 at 6:31

2 Answers 2

6

The usage of preg_match() and preg_match_all() sometimes can be weird

$matches will be array of the matches to the pattern - in this instance if you

preg_match("/\p{Sc}0\.00/","£0.00",$matches);
//$matches[0] => £0.00

or if you add parenthesis () to the pattern you can extract a part

preg_match("/\p{Sc}(0\.00)/","£0.00",$matches);
//$matches[0] => £0.00
//$matches[1] => 0.00

so to solve this problem try this

foreach($sample_array as $key => $value)
{
     if(preg_match("/(\$|\p{Sc})0\.00/",$value))
     {
          unset($sample_array[$key]);
     }
}

Notice the pipe | that denotes $ or £ - if you add another pipe for the euro symbol it will capture that as well - also notice that we are unset()-ing a key in the original array instead of unset()-ing the $matches array

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this, is it then possible I could just change my original pattern to stop it at source instead of running preg_match again? Current pattern: $pattern = '/\p{Sc}\s*\d{1,3}(?:,\d{3})*(?:\.\d+)?/u';
possibly - it looks like you are getting the numbers out in 2 separate parenthesis - check the value of $matches by doing a var_dump($matches) or print_r($matches)
0
function remove_element($arr, $val)

        {

            foreach ($arr as $key => $value)

            {

                if ($arr[$key] == $val)

                {

                unset($arr[$key]);

                }

            }

            return $arr = array_values($arr);

        }

You can use this function these function returns the array elements after delete the specified value.

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.