3
3

More than 5 years have passed since last update.

ページから特定部分だけを取り除く

Posted at

背景

テンプレートの一覧から、ヘッダの部分を一気に置き換えたかったんですが、
手でやるのはあまりにも面倒だったのでPHPでやってみました。

やりたかったこと

  • 修正前のテンプレート (例)
<html>
<head>
<title>テスト</title>
</head>

<body>
<!--contents -->
<div>

<!-- header -->
<div>

<div>
ヘッダ画像
</div>

<div>
ナビゲーションバーとか
</div>

</div>
<!-- /header -->

コンテンツの内容

<!-- contents -->

これのヘッダ部分(<!-- header --> ~ <!-- /header -->)をごそっと他のテンプレートをincludeする形に変えて、
↓みたいな感じにしたかった。

  • 修正後のテンプレート (例)
<html>
<head>
<title>テスト</title>
</head>

<body>
<!--contents -->
<div>

<!-- header -->
{include file='hoge.tpl'}
<!-- /header -->

コンテンツの内容

<!-- contents -->

作ったスクリプト

<?php

$targetFiles = glob("*.tpl");

foreach ($targetFiles as $targetFile) {
    $newBody = replaceHeaderTag($targetFile);

    saveNewFile('out/'.$targetFile, $newBody);
}


// ヘッダ部分を置換したHTMLを返す
function replaceHeaderTag($targetFile)
{
    $body = file_get_contents($targetFile);

    $p1 = strpos($body, '<!-- header -->');
    $p2 = strpos($body, '<!-- /header -->');

    $upperBody = substr($body, 0, $p1+strlen('<!-- header -->'));
    $underBody = substr($body, $p2);

    return sprintf("%s\n{include file='hoge.tpl'}\n%s", $upperBody, $underBody);
}

// 置換したHTMLを保存する
function saveNewFile($targetFile, $body)
{
    $fp = fopen($targetFile, "w");
    fwrite($fp, $body);
    fclose($fp);
}

これで、カレントディレクトリ直下のtplファイルを全て対象にして、
ヘッダ部分を置換したファイルがoutディレクトリ配下に保存されます。

3
3
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
3
3