- Products -


Software


NEWS


Special



- Knowledge -


Category × Tag



- Like -

公開
作成日:2021/10/10
更新日:2022/3/4

【PHP】正規表現で一致した文字列を加工して置換する方法

・正規表現に一致した文字列を抜き出すには、preg_match関数を使う。

・複数存在する場合には、preg_match_all関数を使う。

・置換するには、str_replace関数を使う。


サンプルコード


・文字列($html)からpreタグを取得し、html文字のエスケープを行っている。

・preタグ自体は、エスケープしないという考慮を加えている。


preg_match('/<pre>(.*)<\/pre>/', $html, $match_text);
if ($match_text) {
    $before = array("<pre>", "</pre>");
    $after = array("", "",);
    foreach ($match_text as $tmp) {
        if (strpos($tmp, "<pre>") === 0) {
            // codeタグ内を対象にする
            $tmp_1 = str_replace($before, $after, $tmp);
            // br取り除き、htmlスケープする(目的の文字列へ変換)
            $tmp_2 = htmlspecialchars(str_replace("<br>", "\n", $tmp_1));
            $html = str_replace($tmp_1, $tmp_2, $html);
        }
    }
}


ケース2:抜き出したい文字列が複数存在する場合。


・正規表現で先頭マッチを使用する。?を加える。(.*)→(.*?)
https://www.webdesignleaves.com/pr/php/php_basic_03.php

・ループで処理するように変更。


preg_match_all('/<pre>(.*?)<\/pre>/s', $html, $match_text);
if ($match_text) {
    foreach ($match_text[0] as $tmp) {
        $before = array("<pre>", "</pre>");
        $after = array("", "",);
        if (strpos($tmp, "<pre>") === 0) {
            // preタグ内を対象にする
            $tmp_1 = str_replace($before, $after, $tmp);
            // BR取り除き、htmlスケープする(これが目的の文字列)
            $tmp_2 = htmlspecialchars(str_replace("<br>\r\n", "\n", $tmp_1));
            $html = str_replace($tmp_1, $tmp_2, $html);
        }
    }
}


正規表現テストツール


https://rakko.tools/tools/57/

参考


https://techacademy.jp/magazine/11402
https://liginc.co.jp/programmer/archives/228
https://www.php.net/manual/ja/function.preg-match.php

https://qiita.com/kazu56/items/35c10fdd79393686b26d


Category



Tag




関連記事


{{tmp.name}}

{{article.category}} {{article.title}}