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

时间:2022-04-06 20:08:36

I've searched * far and wide and can't find anything relevant to my situation.

我已经远远地搜索了*,找不到与我的情况相关的任何内容。

I have a booking confirmation letter which is pulled from the DB. the contents of the letter has tags, formatted like so: |SURNAME| |FIRSTNAME| |TRAVELDATE|

我有一张从DB中提取的预订确认函。这封信的内容有标签,格式如下:| SURNAME | | FIRSTNAME | | TRAVELDATE |

and so on. These tags I have stored in the DB as well. What I want to do is, for each tag, find all occurences of that word and replace them with appropriate data for the particular booking, then move onto the next tag and do it again.

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

So far I have come up with (mix of code and pseudo code):

到目前为止,我已经提出了(代码和伪代码的混合):

 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;
 }

I am unable to use str_replace() yet. If the tag has found a match in the confirmation letter, I need to do a call to the DB to grab the appropriate data, and then replace the tag with the appropriate data.

我还不能使用str_replace()。如果标签在确认函中找到了匹配项,我需要调用DB来获取相应的数据,然后用适当的数据替换标签。

1 个解决方案

#1


1  

This might work

这可能会奏效

//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

#1


1  

This might work

这可能会奏效

//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