preg_replaceでreplacement部分をpatternで一致した値を引数にループ処理したかったんだけれど、preg_replace_callback という関数があるのね。
やりたいことの例:
テンプレに↓こう書いてある。
テンプレ.html
<dl>
<dt>○○さんの発言</dt>
<dd>
__%topic_list(77)%__
</dd>
</dl>
<dl>
<dt>××さんの発言</dt>
<dd>
__%topic_list(78)%__
</dd>
</dl>
※__%topic_list(ユーザーID)%__ という形式の部分はそのヒトのトピック発言をループ処理した結果に置き換える。
期待する結果:
<dt>○○さんの発言</dt>
<dd>
<ul>
<li><a href="#">○○○○○○○○○○○○○○○○○○</a></li>
<li><a href="#">○○○○○○○○○○○○○○○○○○</a></li>
<li><a href="#">○○○○○○○○○○○○○○○○○○</a></li>
</ul>
</dd>
</dl>
<dl>
<dt>××さんの発言</dt>
<dd>
<ul>
<li><a href="#">××××××××××××××××××</a></li>
<li><a href="#">××××××××××××××××××</a></li>
<li><a href="#">××××××××××××××××××</a></li>
</ul>
</dd>
</dl>
テンプレを読み込んで preg_replace_callback で変換して出力する:
preg_replace_callback-sample.php
$members_list = file_get_contents("テンプレ.html");
$members_list = preg_replace_callback(
"/__%topic_list\((\d+)\)%__/",
"get_topic_list_from_user_id",
$members_list);
echo $members_list;
function get_topic_list_from_user_id($matches) {
$user_id = $matches[1];
$topics = get_topics($user_id); // ←$user_id の発言が取れるものとする
$topic_list = '<ul>';
foreach ($topics as $topic) {
$topic_list .= '<li><a href="'. $topic['link_url']. '"></>'. $topic['post'] .'</li>';
}
$topic_list .= '</ul>';
return $topic_list;
}