CodeIgniter3中从IMAP邮件内容提取键值对数组求助
Hey there! The problem with using explode("-", $emailBodyContent) is that it splits every single hyphen it finds—including the ones that aren't meant to separate your target key-value pairs. That's why you ended up with jumbled keys and values in your resulting array.
Instead, we can use a targeted regular expression to accurately identify each key-value pair, even for keys with spaces like Terms And Conditions. Here's how to implement this in CodeIgniter3:
Step 1: Clean Up the HTML Content (if needed)
First, if your ['body']['html'] contains HTML tags, strip them out to avoid messing up the regex matching:
// Get the raw HTML content from your IMAP response $emailHtml = $yourImapResponse['body']['html']; // Strip HTML tags to get clean plain text $cleanContent = strip_tags($emailHtml);
Step 2: Use Regex to Extract Key-Value Pairs
We'll use preg_match_all() to find all valid key-value pairs. The regex is built to match multi-word keys followed by -, then capture the value until the next key pair or the end of the string:
// Define the regex pattern to target valid key-value pairs $pattern = '/(\w+(?: \w+)*) - ([^-]+?(?= \w+(?: \w+)* - |$))/'; // Run the regex on the cleaned content preg_match_all($pattern, $cleanContent, $matches); // Build your target associative array $resultArray = []; foreach ($matches[1] as $index => $key) { // Trim extra whitespace from both key and value for cleanliness $resultArray[trim($key)] = trim($matches[2][$index]); } // Check the final result print_r($resultArray);
What the Regex Does
Let's break down the pattern to understand why it works:
(\w+(?: \w+)*): Matches keys with one or more words (e.g.,Title,Customer,Terms And Conditions)-: Explicitly matches the hyphen with spaces on either side—this ensures we only split on the intended key-value separators([^-]+?(?= \w+(?: \w+)* - |$)): Captures the value, stopping either when it hits the next[Key] -pattern or the end of the string (non-greedy matching prevents over-capturing)
Expected Output
Running this code will give you exactly the array you're looking for:
Array ( [Title] => Title Goes Here [Customer] => Mr Abc Xyz [Terms And Conditions] => You must accept our terms and conditions before sign in for any deals and offers. You can refer our detailed information about this. )
This approach works seamlessly in CodeIgniter3 since it uses core PHP functions that are fully supported in the framework.
内容的提问来源于stack exchange,提问作者SRK

