2

I have a list of numbers like this:

123-4-5679 tha
546-5465-7 dsf
98-4564-64 ds8

I want to explode into it's own value while striping everything but the numbers. I am doing but it seems to keep everything but it does give me a value per line

$pn = preg_replace("/\r/", "\n", preg_replace("/\r\n/", "\n", $_POST['phone']));
$phone_numbers = explode("\n", $pn);
4

4 回答 4

4

You can also do it with one quick line in regex.

preg_match_all(":([0-9-]+):mi", $_POST["phone"], $match);

Here's an example

Edit: To remove hyphens iterate through the results and replace the hyphens with an empty string

preg_match_all(":([0-9-]+):mi", $_POST["phone"], $matches);

// remove extra match array
$matches = array_shift($matches);

foreach( $matches as & $match )
{
   $match = preg_replace(":-:", "", $match);
}

Updated example

于 2013-03-08T08:08:07.987 回答
1

I'd strip everything but digits and newlines:

$cleaned = preg_replace("/[^0-9\n]/", "", $_POST['phone']);

And then explode it:

$numbers = explode("\n", $cleaned);
于 2013-03-08T07:59:30.513 回答
0

Keep all numbers, match everything else but the line-separators:

~(?![\d-]+).*~

Usage in PHP to replace each match with an empty string

$numbers = preg_replace("~(?![\d-]+).*~", '', $phone);

Result:

123-4-5679
546-5465-7
98-4564-64
于 2013-03-08T08:18:25.743 回答
-2

Ok am i missing somethins?

$phone = explode(' ', $_POST['phone']);
$phone_number = $phone[0];

Isn't this working?

于 2013-03-08T07:58:57.303 回答