搜索字符串中的单词并仅在匹配时替换

Search for words in a string and replace only if there's a match

我广泛搜索了 Whosebug,但找不到与我的情况相关的任何内容。

我有一封从数据库中提取的预订确认信。信件的内容有标签,格式如下: |姓氏| |名字| |旅行日期|

等等。这些标签我也存储在数据库中。我想要做的是,对于每个标签,找到该词的所有出现并将它们替换为特定预订的适当数据,然后移动到下一个标签并再次执行。

到目前为止我想出了(代码和伪代码的混合):

 function booking_Confirmation_Replace($conn, $confirmation_Email, $gp_ID){
     //Get all tags
     $tag_Array = array();
     if ($stmt = $conn->prepare("SELECT name FROM Booking_Confirmation_Tags ORDER BY name")) {
        $stmt->execute();
        $stmt->bind_result($name);
        while ($stmt->fetch()) {
            $tag_Array[] = $name; //For each tag it finds, add to the array
        }
        $stmt->close();
    }

    //Loop through each tag
    foreach ($tag_Array as $tag) {
        //find occurence of all tags in $confirmation_Email
        if (strpos($tag, $confirmation_Email) !== false) { //not working
            echo 'found occurance of word '.$tag.' <br />';
            //If there's a match, get appropriate data (possible with case statement) and replace tag
        }
        else{
            echo 'no occurance <br />'; 
        }
    } //end foreach
    return $confirmation_Email;
 }

我还无法使用 str_replace()。如果标签在确认信中找到匹配项,我需要调用数据库以获取适当的数据,然后用适当的数据替换标签。

这可能有效

//Loop through each tag
foreach ($tag_Array as $tag) {
    if(strpos($confirmation_Email, $tag) !== false) {
      // fetch appropriate data
      str_replace($tag, $appropriate_data, $confirmation_Email);
    }
} //end foreach