将标签更改为图库

时间:2013-11-18 14:49:28

标签: php str-replace

我需要将变量中的标签[gallery-1]从数据库替换为实际图库。问题是,那个画廊是用标签中的那个数字来表示的(我有多个画廊或类别)。我试过str_replace,但它没有解决数字问题 我需要取这个数字,从图库编号X中选择图像,然后回显它们(根据该数字替换内容)。

2 个答案:

答案 0 :(得分:1)

preg_match_all()是你的朋友:

$code = "<p>Test...test...test...</p> [gallery-1]";

preg_match_all("/\[gallery-(\d+)\]/", $code, $matches);

$galleries = array();

foreach ($matches[1] as $id) {
  $galleries[$id] = // Somehow load a gallery basing on id;
}

foreach ($galleries as $id => $c) {
  $code = str_ireplace("[gallery-" . $id . "]", $c, $code);
}

echo $code;

如果您仍然有疑问,请点击此处an example

答案 1 :(得分:0)

如果你想从字符串[gallery-1](包括括号)中获取整数,请尝试:

$gallery = '[gallery-1]';
echo preg_replace('/\[gallery-(\d+)\]/', '$1', $gallery);