1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

preg_replace_callbackでテンプレ内の複数ヶ所のループ処理を済ませる

Posted at

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;
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?