首页 > 解决方案 > Coldfusion 替换函数或右函数返回一个空格

问题描述

我有这个功能,我需要获取 10 位数的电话号码。

<cffunction name="StandardPhoneNumber" 
                access="public" 
                hint="Returns a 10 digit phone number in a numeric format ex. 8883334444"

                Description="We use a standard numeric only phone number. We stripped the non numeric characters and return 10 digit">
        <cfargument name="phoneNumber" required="true" >

        <!--- we need a little bit of processing here coz of a bug where a space is returned at the start of the number  --->
        <cfset local.phoneNumber = right(REReplace(arguments.phoneNumber, "[^0-9]", "", "ALL"),10) />

        <cfreturn trim(local.phoneNumber)/>
</cffunction>

由于某种原因,返回的值也返回了一些空间。

示例输入值“+5122131151”将返回“5122131151”(5 前面的空格)

添加了替换功能

REReplace(arguments.phoneNumber, "[^0-9]", "", "ALL")

这样它即使带有破折号+1888-333-4444也可以接受电话号码并返回10位电话号码。这仅适用于标准电话号码为 10 位的美国电话号码。

标签: regexcoldfusion

解决方案


首先:不,你的功能不是罪魁祸首。正则表达式[^0-9]去除所有非数字,包括空格。trim函数末尾的 是多余的,甚至不需要。这是一个小提琴来证明它。 如果链接失效,请看最后的附件

+成为空格(空格字符)时,它更有可能与编码问题有关。当文字字符出现在 GET 查询字符串或 POST 有效负载中时,它会+被替换为空格(更多详细信息)。因此,我认为您的输入/输出链中有问题,与功能无关。

另外,我不是美国电话号码以及如何正确处理国家电话代码的专家,但你的方法似乎有点太天真了。例如:如果电话号码少于 10 位,您将保留1国家代码的+1,因为right(number, 10)仍然包含它。当您必须处理国际号码时,情况会更糟,因为国家/地区的呼叫代码可能不止一个数字并且有特殊规则(例如+49,对于德国,0如果存在,则去掉后面的 )。您可能需要考虑这一点。

无论如何,请检查您调用的位置StandardPhoneNumber(),检查您通过的结果的结果,并检查您最终输出的内容。罪魁祸首隐藏在这个链条的某个地方。

附件

<cfset valuesToTest = [
    "1234567890",
    "123-4567-890",
    "+1234567890",
    "+123-4567-890",
    "123",
    "12345678901234567890",
    "  1234567890#chr(9)#"
]>
<cfoutput>
<cfloop array="#valuesToTest#" index="value">
    <cfset newValue = StandardPhoneNumber(value)>
    #value# = #newValue# (length: #len(newValue)#)<br>
</cfloop>
</cfoutput>

<cffunction name="StandardPhoneNumber" 
            access="public" 
            hint="Returns a 10 digit phone number in a numeric format ex. 8883334444"

            Description="We use a standard numeric only phone number. We stripped the non numeric characters and return 10 digit">
    <cfargument name="phoneNumber" required="true">

    <cfset local.phoneNumber = right(REReplace(arguments.phoneNumber, "[^0-9]", "", "ALL"), 10)>

    <cfreturn local.phoneNumber>
</cffunction>

推荐阅读