PHP开发需求:实现字符串匹配包装与截断展示函数
Alright, let's build this PHP function to meet your exact requirements. I'll walk through the logic with clear explanations, plus include example code to test it out.
Solution Code
function highlightAndPreview(string $str, string $wrap, string $text): string { // Validate input first to avoid issues with empty values if (empty($str) || empty($wrap)) { return ''; } // Escape special characters in $str and $wrap for safe regex use $escapedStr = preg_quote($str, '/'); $escapedWrap = preg_quote($wrap, '/'); $wrappedMatch = $escapedWrap . $escapedStr . $escapedWrap; // Wrap all occurrences of $str with the $wrap string $modifiedText = preg_replace("/$escapedStr/", "$wrap$str$wrap", $text); // Regex pattern to capture up to 2 words before, the wrapped match, and up to 2 words after // Includes apostrophes to handle words like "don't" or "Mary's" $previewPattern = "/(?:(\b[\w\']+\b\s*){0,2})($wrappedMatch)(?:(\s*\b[\w\']+\b){0,2})/"; if (preg_match($previewPattern, $modifiedText, $matches)) { $preview = ''; // Add leading ellipsis if the match isn't at the start of the text if (strpos($modifiedText, $matches[0]) !== 0) { $preview .= '...'; } // Append captured context, the wrapped match, and trailing context $preview .= trim($matches[1] ?? '') . ' '; $preview .= $matches[2]; $preview .= ' ' . trim($matches[3] ?? ''); // Add trailing ellipsis if the match isn't at the end of the text $matchEndPos = strrpos($modifiedText, $matches[0]) + strlen($matches[0]); if ($matchEndPos !== strlen($modifiedText)) { $preview .= '...'; } // Clean up extra spaces from context trimming return preg_replace('/\s+/', ' ', trim($preview)); } // Return empty string if no matches are found return ''; }
How It Works
Let's break down each key part:
- Input Validation: We check for empty
$stror$wrapfirst to prevent unexpected behavior from invalid inputs. - Safe Regex Handling:
preg_quoteescapes any special characters (like.,*, or|) in your search and wrap strings, so the regex works reliably even with non-alphanumeric values. - Wrapping Matches:
preg_replacereplaces every instance of$strwith the wrapped version (e.g.,testbecomes|test|). - Preview Extraction: The regex captures up to 2 words before and after the wrapped match. We then check if the match is at the start/end of the text to decide whether to add ellipsis (
...) for context. - Cleanup: We use
preg_replaceto remove extra spaces that might result from trimming context parts.
Example Usage
// Your sample values $str = "test"; $wrap = "|"; $text = "This is a test Text"; // Run the function echo highlightAndPreview($str, $wrap, $text); // Output: ...is a |test| Text...
Edge Cases to Consider
- Case Sensitivity: The current code does exact case matching (so "Test" won't match "test"). If you need case-insensitive matching, add the
imodifier to the regex patterns (e.g.,/pattern/i). - Multiple Matches: This function returns a preview for the first match. If you need to show previews for all matches, modify it to use
preg_match_alland loop through each match to build combined previews. - Short Text: If the match is at the start or end of the text, no leading/trailing ellipsis will be added (e.g., if
$textis "test is here", the output would be|test| is here...).
内容的提问来源于stack exchange,提问作者Milan
相关产品推荐
相关产品推荐

