在文本中查找字符串的第一个匹配项,并返回原始文本样本

问题描述:

我有一个包含各种特殊字符的文本,我需要找到字符串的第一个匹配项,然后返回像这样的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"; 

它应该返回:

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

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

+0

你试过用str_pos()吗?它为您提供了字符串中第一个匹配的位置。然后,你可以猜测你想打印的第一个字符的位置,以及最后一个字符的位置...... – Random

From the PHP manual

strpos - 查找字符串

因此,一个字符串的第一个出现的位置,如果我们使用该功能来定位,我们可以很容易地使用类似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 ( 
+0

谢谢谢里夫,很棒的功能,真正做我需要的! –

这可以用正则表达式来完成。 A .是任何字符(不包括新行),{}是字符限制或范围。在这种情况下,我们将允许任何字符中的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字符。您找到的字符串或说明已关闭。

回报这样的10个字符+第一场比赛+ 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"; 
preg_match('~.{0,10}' . preg_quote($stringToFind, '~') . '.{0,10}~', $text, $match); 
print_r($match); 

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

+0

谢谢克里斯...你有任何建议,如果我的stringToFind是在开始或结束(例如!!)..如果字符串在中间,或者每边至少有10个字符,则效果很好。 (我可以在开头和结尾的原始文本中添加10个额外的空格,然后修剪最终结果,但看起来不怎么漂亮)您怎么看? –

+0

您可以修改范围以使'10'为可选长度。 '(。{0,10} hars/t。{0,10})'在匹配之前和/或之后允许0-10个字符。演示2:https://regex101.com/r/iR3pA6/2您可以在这里阅读更多内容,http://www.regular-expressions.info/repeat.html请参阅“限制重复”。 – chris85

+0

感谢Chris和演示。我真的应该阅读更多关于正则表达式,但我的PHP是非常有限的。 –