本文介绍了如何在插入数据库之前根据第一个字母(表达式)修剪前三个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的php文件

这是我的代码,用于从数据库中检索数据.

This is my code to retrieve data from database.

在这里,我需要根据第一个表达式(+)删除前三个字符,然后删除两个数字,即(91).因此,总的来说,我需要删除数据库中具有+91的电话号码.谁能帮我这个忙.

Here i need to remove first three characters based on the first expression(+) and followed by two numbers i.e(91). So totally i need to remove phone numbers which have +91 in database.Can anyone help me regarding this.

    <?php
    session_start();


    $response = array();

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

    if(!mysqli_connect_errno()){

        $error_flag = false;

    $contacts = json_decode($_POST['contacts'], true);
    foreach($contacts as $contact){

            //$trimmed = $contact['phone'];

            //$title = str_replace("+91", "", trim($trimmed));
            // $prefix = '+91';
            // $str = $contact['phone'];
            // if (substr($str, 0, strlen($prefix)) == $prefix) 
            //     { echo $str = substr($str, strlen($prefix)); }


            $sql = "INSERT INTO contacts (vault_no , name, phone, created_at)
            VALUES ('".$contact['vault_no']."', '".$contact['name']."', REPLACE('".$contact['phone']."','+91',''), NOW())";

                if(mysqli_query($con,$sql)){

                    echo "Successfully Saved";

                }else{
                    $response["error"] = true;
                    $response["error_msg"] = "INSERT operation failed";
                    echo json_encode($response);
                }
                    //}
    }

    }else{
        $response["error"] = true;
        $response["error_msg"] = "Database connection failed";
        echo json_encode($response);
    }
?>

推荐答案

您可以简单地使用 REPLACE() :

You can simply use REPLACE() :

SELECT REPLACE(t.mobile,'+91','') as mobile
FROM YourTable t

或者如果您想在数据库中更改它:

Or if you want to change it in the database :

UPDATE YourTable t
SET t.mobile = REPLACE(t.mobile,'+91','')

这篇关于如何在插入数据库之前根据第一个字母(表达式)修剪前三个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 21:21