我试图从我的市场网站用户之间的消息中删除/检测电话号码(想想eBay做了类似的事情) 这是我使用的代码:
$string = preg_replace('/([0-9]+[\- ]?[0-9]+)/', '', $string);
但是......它过于咄咄逼人,它会用2个或更多数字去除任何数字......如何设置7个数字的限制呢?
更确切地说,电话号码可以是任何格式,如
3747657654
374-7657654
374-765-7654
(374)765-7654
etc...(i cannot predict what the users will write depending of their habits)
答案 0 :(得分:1)
答案 1 :(得分:0)
这取决于确切的要求,因为现在您有一个或多个数字,后跟一个可选的-
或空格,后面再跟一个或多个数字。
如果你想要例如空格前至少2个数字或-
后跟至少5个数字,你可以使用类似的东西:
$string = preg_replace('/([0-9]{2,}[\- ]?[0-9]{5,})/', '', $string);
^^^^ Here you can specify mininimum / maximum
^^^^ Here you can specify mininimum / maximum
答案 2 :(得分:0)
您可以尝试这样的事情:
$string = preg_replace('/(?<![0-9]|[0-9]-)[0-9](?:[- ]?[0-9]){6}(?!-?[0-9])/', '', $string);
这里的外观是为了避免超过7位的数字,但是如果你想要更具体的东西,你应该提供一个示例字符串。
答案 3 :(得分:0)
It is impossible to determine whether a number of X digits (where X is a valid phone number length) is a phone number or something else without some sort of context intelligence happening. A simple regex can't determine the difference between "call me at 3453456" and "call me when you've flown 3453456 miles".
Therefore trying to catch phone numbers without any formatting (just straight digits) with a regex is hopeless, pure and simple. Attempting to do so is only holding you back from finding a regex that can find formatted/semi-formatted numbers. What you should be going for here is "get the obvious and as many others as possible with minimal false positives...but recognize I can't get them all."
For that I'd recommend this:
/1?[ \-]?\(?([0-9]{3})?\)?[ \-]?([0-9]{3})[ \-]([0-9]{4})/g
It should not get the first three, but get all the rest in this list:
no-match: 3747657654
no-match: 444444444444444
no-match: 7657654
match: 374-765-7654
match: 1-374-765-7654
match: (374)765-7654
match: (374) 765 7654
match: 765-7654
match: 1 (374) 765 7654
match: 1(374)765 7654