LoginSignup
1
0

More than 1 year has passed since last update.

文字列から数字だけを取り出すor消す

Last updated at Posted at 2021-10-04

いつもググってた
ttp://djcase.jp/app/mywiki/post/172
に有った記事のコピーです
どうもサイトがなくなってしまったようで・・(泣)

文字列から数字だけを取り出すor消す

数字のみを「消す」場合

$target = 'アッカリーン0120はーい!0930';
$target = preg_replace("/[0-9]/", "", $target);
echo $target;

上記の結果は

アッカリーンはーい!

正規表現を使って置換できるpreg_replaceを使用。[0-9]は「0から9までの数字」という意味。

$targetに対して「0から9までの数字」を空文字で置換(=消す)している。

preg_replace関数について
https://www.php.net/manual/ja/function.preg-replace.php

数字のみを「取り出す」場合

$target = 'アッカリーン0120はーい!0930';
$target = preg_replace("/[^0-9]/", "", $target);
echo $target;

上記の結果は

01200930

[0-9]は「0から9までの数字」だったが^が付く事で否定になる。

$targetに対して「0から9までの数字」以外を空文字で置換(=消す)している。

preg_replace関数について
https://www.php.net/manual/ja/function.preg-replace.php

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0