PHPで文字列から数値のみ取り出す
PHPで文字列から数値のみを取り出すには、preg_replace()メソッドを使います。
//取り出したい文字列 $string = 'ST1002E'; //0-9以外の文字を空白に置換 $num = preg_replace('/[^0-9]/', '', $string); echo $num; // 1002
greg_replace()の引数は下のように指定します。
preg_replace(検索の対象, 置換後の文字, 文字列);
検索の対象には普通に文字列を指定することもできますが、正規表現で指定することもできます。ここでは正規表現を使って、数値以外の文字を空白に置換することで文字列から数値のみを取り出しています。
greg_replace()の仕様は下記の公式ドキュメントで確認できます。
PHP: preg_replace - Manual
PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites i...
コメント