文字列から数値のみを抜き取る

このエントリーをはてなブックマークに追加
はてなブックマーク - 文字列から数値のみを抜き取る
Share on Facebook

コード

/**
 * 文字列から数字のみを抜き取る
 *
 * @param  string  $str  チェックしたい文字列
 * @return string  数字のみになった文字列
 * @see <a href="http://mbnk.blog120.fc2.com/blog-entry-58.html">モバイルサイト開発者の裏メモ  PHP 文字列から数字のみを抜き取る</a>
 */
function extract_numbers($str) {
    return preg_replace('/[^0-9]+/', '', $str);
}

実行サンプル

<?php
/**
 * 文字列から数字のみを抜き取る
 *
 * @param  string  $str  チェックしたい文字列
 * @return string  数字のみになった文字列
 * @see <a href="http://mbnk.blog120.fc2.com/blog-entry-58.html">モバイルサイト開発者の裏メモ  PHP 文字列から数字のみを抜き取る</a>
 */
function extract_numbers($str) {
    return preg_replace('/[^0-9]+/', '', $str);
}

$strs = array(
    "03-3200-2222",
    "uso800",
    "Attack25",
    "500 Miles High",
    "99999999",
    "R2-D2",
);

foreach ($strs as $key => $tel) {
    echo "{$key}: {$tel} -> ";
    echo lfExtractNumber($tel);
    echo "\n";
}
/** End of file */

実行結果

$ php extract_number.php
0: 03-3200-2222 -> 0332002222
1: uso800 -> 800
2: Attack25 -> 25
3: 500 Miles High -> 500
4: 99999999 -> 99999999
5: R2-D2 -> 22

参考

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>