在php

时间:2017-01-31 07:29:01

标签: php

所以我正在开发一个系统来替换字符串中的占位符。

字符串示例:

$string = 'Meatloaf beef landjaeger porchetta swine t-bone boudin salami doner turkey capicola. [IMG1] Pork loin doner capicola chicken filet mignon. Swine sausage sirloin short ribs bresaola bacon picanha kielbasa fatback. Andouille turducken pastrami, beef ribs bacon chicken biltong t-bone pancetta spare ribs shankle pork belly ground round brisket. Pastrami pork t-bone bresaola shoulder. Landjaeger short ribs tenderloin kielbasa, [IMG3] shank picanha spare ribs pig chuck. Sausage pastrami [billede1] kielbasa pig meatloaf t-bone shankle jowl tongue ham hock tail cow.';

每个字符串都包含[IMG1],其中的数字将引用我需要在数据库中查找的ID。

所以我们的目标是找到每个id并用图像url替换每个“tag”。

  • 如何遍历字符串以获取al标记,然后使用新值放置它们?

  • 每个字符串都有不同的占位符[IMG + randomNumber],所以我需要找到每个ID,所以我可以用它来查找我的数据库中的图像名称等。

3 个答案:

答案 0 :(得分:0)

将url值分配给变量并将变量插入字符串而不是标记。

$IMG1 = "<some url>";
$string = "Meatloaf beef landjaeger porchetta swine t-bone boudin salami doner turkey capicola. [$IMG1]";

答案 1 :(得分:0)

尝试使用preg_replace_callback()功能:

<?php
$string = 'Meatloaf beef landjaeger porchetta swine t-bone boudin salami doner turkey capicola. [IMG1] Pork loin doner capicola chicken filet mignon. Swine sausage sirloin short ribs bresaola bacon picanha kielbasa fatback. Andouille turducken pastrami, beef ribs bacon chicken biltong t-bone pancetta spare ribs shankle pork belly ground round brisket. Pastrami pork t-bone bresaola shoulder. Landjaeger short ribs tenderloin kielbasa, [IMG3] shank picanha spare ribs pig chuck. Sausage pastrami [billede1] kielbasa pig meatloaf t-bone shankle jowl tongue ham hock tail cow.';


$string = preg_replace_callback(
'/\[.*?\]/',
function ($matches) {
    if(stristr($matches[0], '[IMG') !== FALSE) {
        $tag = substr($matches[0],1,-1);
        $id = (int)str_replace('IMG','',$tag);
        return "<img src='imageurl-".$id."'>";
    }elseif($matches[0] == '[billede1]'){
        return "billede1-REPLACED";
    }

},
    $string
);

echo $string;

答案 2 :(得分:0)

事先定义&#34; 替换列表&#34;(查找表),否则应为每个找到的占位符发送数据库查询。
使用{{1}的解决方案功能:

preg_replace_callback

输出:

$lookup_list = [
    'IMG1' => 'image1.jpg',
    'IMG2' => 'image2.jpg',
    'IMG3' => 'image3.jpg',
];

$string = 'Meatloaf beef landjaeger porchetta swine t-bone boudin salami doner turkey capicola. [IMG1] Pork loin doner capicola chicken filet mignon. Swine sausage sirloin short ribs bresaola bacon picanha kielbasa fatback. Andouille turducken pastrami, beef ribs bacon chicken biltong t-bone pancetta spare ribs shankle pork belly ground round brisket. Pastrami pork t-bone bresaola shoulder. Landjaeger short ribs tenderloin kielbasa, [IMG3] shank picanha spare ribs pig chuck. Sausage pastrami [billede1] kielbasa pig meatloaf t-bone shankle jowl tongue ham hock tail cow.';

$replaced = preg_replace_callback("/\[(\w+)\]/", function($m) use($lookup_list) {
    return (isset($lookup_list[$m[1]]))? $lookup_list[$m[1]] : $m[0];
}, $string);


print_r($replaced);