LoginSignup
1
0

More than 3 years have passed since last update.

文字列を検索、置換を行う

Posted at

特定のパターンで文字列の検索、もしくは置換をする方法です。
下記の例から電話番号の箇所を探すとします。

その際に使用するのが preg_match('検索したいパターン', '検索したい文字列', '検索した結果を格納する変数'); を使用します。

main.php
<?php

$input = 'Call at 03-1234-5678 or 03-8765-4321';
$pattern = '/\d{2}-\d{4}-\d{4}/';

preg_match($pattern, $input, $matches);
print_r($matches);
ターミナル
~ $ php main.php
Array
(
    [0] => 03-1234-5678
)

結果として最初に見つかった結果だけを matches に格納してくれます。全て見つけたい場合は $preg_match_all() を使います。

main.php
<?php

$input = 'Call at 03-1234-5678 or 03-8765-4321';
$pattern = '/\d{2}-\d{4}-\d{4}/';

preg_match_all($pattern, $input, $matches);
print_r($matches);
ターミナル
Array
(
    [0] => Array
        (
            [0] => 03-1234-5678
            [1] => 03-8765-4321
        )

)

次に電話番号を伏字に置換します。

main.php
<?php

$input = 'Call at 03-1234-5678 or 03-8765-4321';
$pattern = '/\d{2}-\d{4}-\d{4}/';

$input = preg_replace($pattern, '**-****-****',$input);
echo $input . PHP_EOL;
ターミナル
$ php main.php
Call us at **-****-**** or **-****-****

参考文献

1
0
0

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