在文本和 return 个原始文本示例中查找字符串的第一个匹配项

Find the first match for a string in text and return sample of original text

我有一个包含各种特殊字符的文本,我需要找到字符串的第一个匹配项,然后 return 类似这样的 10 个字符 + 第一个匹配项 + 10 个字符。换句话说,第一个匹配项位于中间的文本样本。

示例:

$text = "+!This is a text with some % special chars/text and ( for a string query to match. Then !! mor&&&e and so on...chars/text.";
$stringToFind = "hars/t";

应该return:

$grabtext = "% special chars/text and ( for";

我做了一个字符串的例子,发现它不是一个完整的单词并且有 1 个特殊字符。

这可以用正则表达式来完成。 . 是任何字符(不包括新行),{} 是字符限制或范围。在这种情况下,我们将允许 10 个任意字符,.{10}.

~(.{10}hars/t.{10})~

正则表达式演示:https://regex101.com/r/iR3pA6/1

PHP 演示:https://3v4l.org/UBKIS

用法:

$text = "+!This is a text with some % special chars/text and ( for a string query to match. Then !! mor&&&e and so on...chars/text.";
$stringToFind = "hars/t";
preg_match('~.{10}' . preg_quote($stringToFind, '~') . '.{10}~', $text, $match);
print_r($match);

注意这个 special c 是 10 个字符,hars/text 是你的匹配项,ext and ( 是额外的 10 个字符。您找到的字符串或说明已关闭。

return something like this 10 chars + first match + 10 chars

更新,最多允许 10 个字符使用:

$text = "+!This is a text with some % special chars/text and ( for a string query to match. Then !! mor&&&e and so on...chars/text.";
$stringToFind = "hars/t";
preg_match('~.{0,10}' . preg_quote($stringToFind, '~') . '.{0,10}~', $text, $match);
print_r($match);

演示:https://regex101.com/r/iR3pA6/2

From the PHP manual

strpos — Find the position of the first occurrence of a substring in a string

因此,如果我们使用该函数来定位子字符串的偏移量,我们可以轻松地使用类似 substr 的方法从该偏移量中获取 +/- 10 个字符的子字符串。

function grabText($string, $searchString) {
    if (($x = strpos($string, $searchString)) === false) {
        return; // no match found
    }
    $y = strlen($searchString) + 20;
    $x = max(0, $x - 10);
    return substr($string, $x, $y);
}

$text = "+!This is a text with some % special chars/text and ( for a string query to match. Then !! mor&&&e and so on...chars/text.";
$stringToFind = "hars/t";
echo grabText($text, $stringToFind); //  special chars/text and (