You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 $str or $wrap first to prevent unexpected behavior from invalid inputs.
  • Safe Regex Handling: preg_quote escapes any special characters (like ., *, or |) in your search and wrap strings, so the regex works reliably even with non-alphanumeric values.
  • Wrapping Matches: preg_replace replaces every instance of $str with the wrapped version (e.g., test becomes |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_replace to 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 i modifier 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_all and 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 $text is "test is here", the output would be |test| is here...).

内容的提问来源于stack exchange,提问作者Milan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:09:07