1

我正在尝试创建一个简化的代码,以基于类似于 BBCode 的用户输入将图像动态插入页面。

例如,如果我的一个用户输入“我喜欢鸭子 [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 只查找一个。我尝试创建一个循环(while & foreach w/preg_match_all)来尝试测试这个概念——两者都创建了无限循环,我的网络服务器管理员不太高兴:p

4

1 回答 1

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;
于 2011-02-08T22:03:35.300 回答