- substr: documentation ( source)
- strpos: documentation ( source)
<?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;