我正在尝试使用正则表达式从字符串中挑选电话号码,其中电话号码的格式可能只是任何内容,或者可能没有电话数字。例如:从字符串中挑选电话号码(正则表达式)
$string = 'My phone number is +34 961 123456.';
$string = 'My phone number is +34 (961) 123456.';
$string = 'My phone number is 961-123456.';
$string = 'My phone number is +34.961.12.34.56.';
$string = 'Product A costs €100.00 and Product B costs €134.15.';
到目前为止,我得
$number = preg_replace("/[^0-9\/\+\.\-\s]+/", "", $string);
$number = preg_replace("/[^0-9]+/", "", $number);
if (strlen($number)>8) {
/* It's a phone number, so do something with it */
}
这适用于挑选出所有的,我已经尝试了不同的电话号码格式,但它也把价格一起,并假定他们也是一个电话号码。
看来我的问题是,一个人可以很容易区分单词和电话号码中间的空格之间的空间,但我该如何让电脑做到这一点?有没有办法可以替换数字前后的空格,但保留其他空格不变?有没有其他的方法来整理呢?
“重复”问题的答案仅适用于输入中的所有数字都属于电话号码 – alexis
而不是“+”的情况。使用量词应该有助于“{n,}”(n或更多次) –