0

我试了又试,但我很难过。假设我有以下场景:

$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 中实现这一点。帮助?

4

1 回答 1

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 个字符 + 关键字长度的 $result。如果您希望它仅为 136,请添加$length = 136 - strlen($keyword);

于 2013-03-09T07:52:32.757 回答