Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
992 views
in Technique[技术] by (71.8m points)

php regex, extract phone numbers from string?

i am having a small problem with my regex which i use to extract phone numbers from a strong

<?php
$output = "here 718-838-3586 there 1052202932 asdas dasdasd 800-308-4653 dasdasdasd 866-641-6949800-871-0999";
preg_match_all('/[0-9]{3}s*[-]?s*[0-9]{3}s*[-]?s*[0-9]{4}/',$output,$matches);
echo '<pre>';
print_r($matches[0]);
?>

output

Array
(
            [0] => 718-838-3586
            [1] => 1052202932
            [2] => 800-308-4653
            [3] => 866-641-6949
            [4] => 800-871-0999

)

this work fine but it returns 1052202932 as one of result which i don't need .
actually i don't know where is the missing part in my pattern .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ? after each [-] is making the - optional. If you want it to be required you can just remove the ? which will make it required. Also, [-] is equivalent to - so I got rid of the unnecessary character class:

preg_match_all('/[0-9]{3}s*-s*[0-9]{3}s*-s*[0-9]{4}/',$output,$matches);

You can also replace all of the [0-9] with d to shorten it a bit further:

preg_match_all('/d{3}s*-s*d{3}s*-s*d{4}/',$output,$matches);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...