用图像替换动态文本

时间:2011-02-08 21:53:22

标签: php mysql preg-match str-replace

我正在尝试创建一个简化的代码,以根据类似于BBCode的用户条目动态地将图像插入到页面中。

例如,如果我的一个用户输入“我喜欢ducks [image] ducks [/ image]”,我想爆炸[image] ducks [/ image],在MySQL中搜索关键字“ducks”,拉图像路径&来自匹配的数据库的名称,然后显示图像HTML代码以及图像的源。

function image_replace($dimg){
    list($title) = explode("[image]",$dimg);
    $query_image = mysql_query("SELECT * FROM images WHERE image_title LIKE '%$title%'");
    $fetch_image = mysql_fetch_array($query_image);
    $image_path = $fetch_image['image_path'];
    $image_filename = $fetch_image['image_filename'];
    $image_source = $image_path.$image_filename;
    $dimg = str_replace("[image]","<img src=\"$image_source\">", $dimg);
    $dimg = str_replace("[/image]","</img>", $dimg);
    $dimg = str_replace("$title", "", $dimg);
    return $img;
  }

image_replace($ducks);

我正在讨论的是如何替换动态生成的页面中的文本(如果存在的话) - 如果代码不存在则保留内容。有什么想法吗?


编辑 - 使问题复杂化:

感谢您的帮助!我使用您的输入来执行以下功能:

function image_replace($string){
    $matches = array();
    preg_match('/\[image\](.*)\[\/image\]/', $string, $matches);
    $image = $matches[1];
    $query_image = mysql_query("SELECT * FROM images WHERE image_title LIKE '%$image%'");
    $fetch_image = mysql_fetch_array($query_image);
    $image_path = $fetch_image['image_path'];
    $image_filename = $fetch_image['image_filename'];
    $image_source = $image_path.$image_filename;
    $image_url = "<img src=\"$image_source\"></img>";
    $new_string = preg_replace('/\[image\](.*)\[\/image\]/', $image_url, $string);

    return $new_string;
  }

无论发生多少个实例,我都需要这个工作(因此如果我的用户写了[image] duck [/ image]然后两个句子写了[image] cow [/ image],我希望这个函数替换它们各自的结果)。就像现在一样,有多个实例,它的错误(不是有效的SQL资源)是有意义的,因为preg_match只查找一个。我尝试创建一个循环(而&amp; foreach w / preg_match_all)来尝试测试这个概念 - 两者都创建了无限循环,我的网络服务器管理员也不太高兴:p

1 个答案:

答案 0 :(得分:1)

我会尝试使用preg_match来获取image_url和preg_replace来替换它:

$string = 'I like ducks [image]ducks[/image]';
echo 'Before: ' . $string . '<br />';
$matches = array();
preg_match('/\[image\](.*)\[\/image\]/', $string, $matches);
$image = $matches[1];
//Lookup image_url and throw it in an <img>
$image_url = 'http://blah.com'; //Don't forget <img>
$new_string = preg_replace('/\[image\](.*)\[\/image\]/', $image_url, $string);
echo 'After: ' . $new_string;

修改

$string = "<br />I like ducks [image]ducks[/image]<br />I like cows [image]cows[/image]<br />I like pigs [image]pigs[/image]";
echo 'Before: ' . $string . '<br />';

$matches = array();
preg_match_all('/\[image\]([^\[]*)\[\/image\]/', $string, $matches);
$image_names = $matches[1];
foreach($image_names as $image_name) {
    //Perform your lookup on each name
    //If it is valid perform the replace
    //Gonna say cows isn't there to test
    if($image_name != 'cows') {
        $image_url = 'http://blah.com'; //result of lookup
        $string = preg_replace('/\[image\]' . $image_name . '\[\/image\]/', $image_url, $string);
    }
}
echo 'After: ' . $string;