somejkuser
somejkuser

Reputation: 9040

Compare two digits elegant solution

I have the following two variables:

$addressphone='5612719999';
$googlephone='561-271-9999';

Is there an elegant solution in PHP that can validate that these two variables actually are equal. I'd prefer not to use str_replace as the conditions can change and I'd have to account for everything.

I've tried casting and intval but neither seemed to work

UPDATE

$addressphone='5612719999';
$googlephone='561-271-9999';
preg_replace("/\D/","",$googlephone);
var_dump($googlephone);

returns string(12) "561-271-9999"

Upvotes: 2

Views: 116

Answers (5)

Progrock
Progrock

Reputation: 7485

Remove everything that isn't a digit:

<?php

$addressphone ='5612719999';
$googlephone  ='561-271-9999';

$number_wang = function($numberish) {
    return preg_replace('/[^0-9]/', '', $numberish);
};

assert($number_wang($googlephone) == $addressphone);

Upvotes: 0

Ananda G
Ananda G

Reputation: 2539

$pieces = explode("-", $googlephone);
$newstring=""; 
foeach ($piece in $pieces)
{
$newstring +=piece;
}

Now compare your string with $newstring.

Upvotes: 0

Tarun Vashisth
Tarun Vashisth

Reputation: 96

Try this :

print_r($addressphone === implode("", explode("-",$googlephone)))

Upvotes: 0

Jonathan Lam
Jonathan Lam

Reputation: 17351

I'm kind of reiterating what the comments say, but you should remove the non-digits from each string and them compare their integer values.

// original, non-integer-infested strings
$addressphone= "5612719999";
$googlephone= "561-271-9999";

// remove non-digits
$addressphone = preg_replace("/\D/","",$addressphone);
$googlephone = preg_replace("/\D/","",$googlephone);

and then you can check the following condition for equality:

// compare integer values of digit-only strings
intval($addressphone) == intval($googlephone)
// should return true

Upvotes: 2

Jon
Jon

Reputation: 1085

I would use preg_replace() to remove all non-numeric characters. That way, you're just working with numeric strings, which you can compare any way you'd like.

<?php
    $testString = "123-456-7890";
    echo preg_replace("/\D/", "", $testString); //echos 1234567890
?>

Upvotes: 0

Related Questions