How can the length parameter in the substr function be correctly calculated when isolating text before and after a specific term?

When isolating text before and after a specific term using the substr function in PHP, the length parameter can be calculated by finding the position of the term in the string and subtracting it from the total length of the string. This ensures that the correct number of characters are included in the substr function to capture the desired text.

$string = "This is a sample string with a specific term in it.";
$term = "specific term";
$position = strpos($string, $term);
$length_before = $position;
$length_after = strlen($string) - $position - strlen($term);

$text_before = substr($string, 0, $length_before);
$text_after = substr($string, $position + strlen($term), $length_after);

echo "Text before term: " . $text_before . "\n";
echo "Text after term: " . $text_after;