从字符串中查找特定文本并将其与数据库匹配

时间:2018-12-02 10:00:31

标签: php mysql regex

我有一个网站,人们可以在其中创建食谱,并且可以在创建食谱时将配料逐步添加,我希望突出显示在每个步骤中添加的配料并与数据库匹配,以便我可以更改重量并将其与配料链接详细信息等。

因此,当用户为配料中的步骤编写文本时,就是这样

  

在此步骤中,您需要添加[400克水{65}]和[10克油{61}]煮沸   持续30分钟。

     

其中[400克水{65}] 400克是水的重量,是   仅向用户显示的成分, {65}是数据库中的ID   我待会再匹配

我现在正在做什么

  

测试

 $text="Pour 1 cup of the cream into a saucepan 
and add the sugar, salt. Scrape the seeds of the vanilla bean into the pot and then add the vanilla pod to the pot. Warm the 
mixture over medium heat, just until the sugar dissolves. Remove from the heat and add the remaining cream, milk, and 
vanilla. Stir to combine and chill in the refrigerator.[100g water{64}] [40g oil{61}] ";
    $text2=$text;
    $checkid=substr_count("$text2",'[');
        while ($checkid > 0){
    $pos = strpos($text2, '{');
    $pos2 = strpos($text2, '}');
    $pos3=$pos2-$pos-1;
    $datas=substr($text2,$pos+1,$pos3);

    $datas2=substr($text2,$pos+1,$pos3);
        $getdatas_dats=mysqli_query($conn,"select rising,riswei,inname from recipe_ing_steps r,ingre i where r.risid='$datas' and r.rising=i.inid");
        $thedatass=mysqli_fetch_array($getdatas_dats);
        $string=" <a href='#'>".$thedatass['riswei'].' grams of '.$thedatass['inname']."</a> ";
            $text2=preg_replace("/\[[^]]+\]/","",$text2,1); 
            echo $string;
            $checkid --;
        }

这给了我数据库中两种成分的名称,但是我想要的小麦是用每个文本中受人尊敬的字符串替换每个 [400g水{65}]

1 个答案:

答案 0 :(得分:0)

$text="Pour 1 cup of the cream into a saucepan and add the sugar, salt. Scrape the seeds of the vanilla bean into the pot and then add the vanilla pod to the pot. Warm the mixture over medium heat, just until the sugar dissolves. Remove from the heat and add the remaining cream, milk, and vanilla. Stir to combine and chill in the refrigerator.[100g water{64}] [400g water{65}] ";
$text2=$text;
$checkid=substr_count("$text2",'[');
    while ($checkid > 0){
$pos = strpos($text2, '{');
$pos2 = strpos($text2, '}');
$pos3=$pos2-$pos-1;
$datas=substr($text2,$pos+1,$pos3);

    $getdatas_dats=mysqli_query($conn,"select rising,riswei,inname from recipe_ing_steps r,ingre i where r.risid='$datas' and r.rising=i.inid");
    $thedatass=mysqli_fetch_array($getdatas_dats);
    $string=" <a href='#'>".$thedatass['riswei'].' grams of '.$thedatass['inname']."</a> ";
        $text2=preg_replace("/\[[^]]+\]/","$string",$text2,1); 
        $checkid --;
    }
echo $text2;

这很好