根据关键字从固定长度的文本中提取字符串

时间:2013-03-09 07:41:19

标签: php search center keyword

我尝试过但我很难过。假设我有以下情况:

$string = "Jenny's garden is one of the best in town, it has lush greens and colorful flowers. With what happened to her recently, she could use a new sprinkler system so that she does not have to over exert herself. Perhaps Joel can sell that extra bike to raise money or perhaps put up a garage sale.";

$keyword = "recently";

$length = 136;

// when keyword keyword is empty
$result = "Jenny's garden is one of the best in town, it has lush greens and colorful flowers. With what happened to her recently, she could use a (snip)";

// when keyword is NOT empty
$result = "(snip)it has lush greens and colorful flowers. With what happened to her recently, she could use a new sprinkler system so that she does not h(snip)";

我要做的是获取一个字符串的摘录,如$ result所示,可能以第一次出现的关键字为中心(如果存在)。我很困惑如何使用substr和strpos在php中实现这一点。帮助

1 个答案:

答案 0 :(得分:1)

这应该适合您的需要:

if ($keyword != "") {
    $strpos = strpos($string, $keyword);
    $strStart = substr($string, $strpos - ($length / 2), $length / 2);
    $strEnd = substr($string, $strpos + strlen($keyword), $length / 2);

    $result = $strStart . $keyword . $strEnd;
}
else {
    $result = substr($string, 0, $length);
}

以下是我使用的测试代码:

<?PHP
$string = "Jenny's garden is one of the best in town, it has lush greens and colorful flowers. With what happened to her recently, she could use a new sprinkler system so that she does not have to over exert herself. Perhaps Joel can sell that extra bike to raise money or perhaps put up a garage sale.";

$keyword = "recently";

$length = 136;

if ($keyword != "") {
    $strpos = strpos($string, $keyword);
    $strStart = substr($string, $strpos - ($length / 2), $length / 2);
    $strEnd = substr($string, $strpos + strlen($keyword), $length / 2);

    $result = $strStart . $keyword . $strEnd;
}
else {
    $result = substr($string, 0, $length);
}

echo $result;
?>

这是与之相呼应的结果:

它有郁郁葱葱的绿色和五颜六色的鲜花。根据她最近发生的事情,她可以使用新的喷水灭火系统,这样她就不必

编辑:修复了我的代码中的几个错误......

注意:这将显示$ 136结果,即136个字符+关键字的长度。如果您希望它只有136,请添加$length = 136 - strlen($keyword);

相关问题