1

我想在数据库中记录人们的电话号码。由于人们输入的数字不同(基于区号)等,我想在输入数据库之前将他们输入的任何内容标准化为标准方式,然后当我从数据库中读回它并放在页面上时,它就来了像这样1-954-999-9999以这种格式输出,然后我可以附加<a href="tel:1-954-999-9999">1-954-999-9999</a>并且可以从网络应用程序/或普通站点单击以拨打电话。

说了这么多,我有一个问题。

在 POST 上,这就是我处理它的方式

$compBizNumber = mysqli_real_escape_string($c2d, $_POST['compBizNumber']) ;
$compBizNumber = str_replace("(", "-", $compBizNumber);
$compBizNumber = str_replace(")", "-", $compBizNumber);
$compBizNumber = str_replace(" ", "-", $compBizNumber);
$compBizNumber = filter_var($compBizNumber,FILTER_SANITIZE_NUMBER_INT) ;

有没有办法一次性替换多个字符?

我该怎么办?

提前致谢。

4

2 回答 2

2

str_replace接受一个数组作为第一个(和第二个参数),所以这样做:

$compBizNumber = str_replace(array("(", ")", " "), "-", $compBizNumber);

However, a more flexible way would be to use a regular expression to replace all non-numeric characters:

$compBizNumber = preg_replace("/[^0-9]/", "-", $compBizNumber);

This way you don't have to add all possible characters a user would enter into str_replace.

于 2013-03-30T11:39:20.490 回答
1

Why not use a regex to remove all except numbers:

$myNumber = "+31 (0) 43 - 123 345 67";
preg_replace("/[^0-9]/","", $myNumber);

http://codepad.org/30vUqWWC

However, beware of the + I guess you'd have to replace that with 00 instead of nothing in order to make the number work? Not 100% sure about that one.

于 2013-03-30T11:42:16.930 回答