この回答preg_match
は、データの再構築に関する問題に対処しているようです。しかし、その回答に投稿された正規表現は、ここで説明されている種類のデータ クリーンアップにはあまり適していません。
したがって、公式のPHPドキュメントの投稿からいくつかの優れた正規表現を使用する、私がまとめたその回答のこのバリエーションを試してください。
// Set test data.
$test_data = array();
$test_data[] = '1 800 555-5555';
$test_data[] = '1-800-555-5555';
$test_data[] = '800-555-5555';
$test_data[] = '(800) 555-5555';
// Set the regex.
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';
// Roll through the test data & process.
foreach ($test_data as $data) {
if (preg_match($regex, $data, $matches)) {
// Reconstruct the number based on the captured data.
echo "New number is: " . $matches[1] . '-' . $matches[2] . '-' . $matches[3] . '<br />';
// Dump the matches to check what is being captured.
echo '<pre>';
print_r($matches);
echo '</pre>';
}
}
preg_match
一致を含むクリーンな結果は次のようになります。
New number is: 800-555-5555
Array
(
[0] => 1 800 555-5555
[1] => 800
[2] => 555
[3] => 5555
)
New number is: 800-555-5555
Array
(
[0] => 1-800-555-5555
[1] => 800
[2] => 555
[3] => 5555
)
New number is: 800-555-5555
Array
(
[0] => 800-555-5555
[1] => 800
[2] => 555
[3] => 5555
)
New number is: 800-555-5555
Array
(
[0] => (800) 555-5555
[1] => 800
[2] => 555
[3] => 5555
)