If else condition to replace value in php

I had a php script to run the if else to replace the value based on condition:

//$mobile = '23456701';
$mobile = '01234567';

$zero_lead = "/^01/";
$country_code = "44";


$phone = preg_replace($zero_lead, $country_code, $mobile);

if (strpos($phone, '/^0/') !== true) {
   
   $accountNumber = $mobile;
   
}
else
{
    $accountNumber = '';
}

$post_data = array(
                'phone' => $phone,
                'accountNumber' => $accountNumber,
            );

echo json_encode($post_data);

return: {"phone":"44234567","accountNumber":"01234567"}

my expected return if $mobile = '01234567'; will return {"phone":"44234567","accountNumber":""}

and $mobile = '23456701';will return {"phone":"23456701","accountNumber":"23456701"}

any one have suggestion?

Thanks

2 answers

  • answered 2020-06-27 04:33 user1597430

    PHP is not JS, so you can't use RegExp expressions in primitive functions such as strpos.

    $mobile = '01234567';
    $account = $mobile;
    $country_code = '44';
    
    if (substr($mobile, 0, 2) === '01')
    {
        $account = '';
        $mobile = $country_code . substr($mobile, 2);
    }
    
    echo json_encode
    ([
        'phone' => $mobile,
        'accountNumber' => $account
    ]);
    

  • answered 2020-06-27 05:08 Nick

    You can use the $count parameter to preg_replace to see if a replacement was made (i.e. the $mobile value started with 01), and then use that to set the value of $accountNumber:

    $phone = preg_replace($zero_lead, $country_code, $mobile, -1, $count);
    $accountNumber = $count ? '' : $mobile;
    

    Demo on 3v4l.org