Last active
October 7, 2023 11:34
-
-
Save nagiyevelchin/5704799824e9bd5bebeca018b5c34b0a to your computer and use it in GitHub Desktop.
This PHP function, subStringByLastNBSP, is designed to extract a substring from a given input string while ensuring that the resulting substring does not exceed a specified maximum length ($max). It also considers a minimum length ($min) that the substring should have before attempting to find the last non-breaking space character (' ') within t…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Extracts a substring from a given string, ensuring it does not exceed a maximum length, | |
* and ends at the last occurrence of a non-breaking space character (' ') within the specified range. | |
* | |
* @param string $string The input string to extract the substring from. | |
* @param int $max The maximum length of the substring. | |
* @param int $min The minimum length of the substring before considering the last non-breaking space. | |
* @param string $endstring Optional: The string to append to the extracted substring. | |
* | |
* @return string The extracted substring. | |
*/ | |
function subStringByLastNBSP($string, $max, $min, $endstring = "") { | |
// Check if the input string is already shorter than or equal to the maximum length. | |
if (mb_strlen($string) <= $max) { | |
return $string; | |
} | |
// Extract the substring up to the maximum length. | |
$str = mb_substr($string, 0, $max, "utf8"); | |
// Extract a sub-substring starting from the minimum length. | |
$son = mb_substr($str, $min, $max, "utf8"); | |
// Find the position of the last space character (' ') within the sub-substring. | |
$say = mb_strpos($son, " ", 0, "utf8"); | |
// Calculate the new length based on the last space position and the minimum length. | |
$say = $say + $min; | |
// Truncate the substring to the new calculated length and append the optional endstring. | |
$str = mb_substr($str, 0, $say, "utf8"); | |
$str .= $endstring; | |
return ($str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment