Search code examples
phpsearchcenterkeyword

Extract string from text of fixed length based on keyword


I tried and tried but I'm stumped. Suppose I have the following scenario:

$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)";

What I'm trying to do is get an excerpt of string as shown on $result possibly centering the first occurrence of a keyword (if it exists). I'm baffled how to achieve this in php using substr and strpos. Help?


Solution

  • This should work for what you need:

    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);
    }
    

    Here is the test code I used:

    <?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;
    ?>
    

    And here is the result that was echoed:

    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

    EDIT: Fixed a couple bugs in my code...

    NOTE: This will dispaly a $result that is 136 characters + the length of the keyword. If you want it to only be 136, add $length = 136 - strlen($keyword);