Jyxo\StringUtil::cut PHP Method

cut() public static method

Trims at word boundaries (all non-alphanumeric characters are considered delimiters). If the given string is trimmed, an "etc" is added at the end. Its length is also considered.
public static cut ( string $string, integer $max = 50, string $etc = '...' ) : string
$string string Trimmed string
$max integer Maximum length
$etc string "etc" definition
return string
    public static function cut(string $string, int $max = 50, string $etc = '...') : string
    {
        // Trim whitespace
        $string = trim($string);
        // No trimming is needed
        if (mb_strlen($string, 'utf-8') <= $max) {
            return $string;
        }
        // Find out "etc" length
        switch ($etc) {
            case '&hellip;':
                $etcLength = 1;
                break;
            default:
                $etcLength = mb_strlen(html_entity_decode($etc, ENT_COMPAT, 'utf-8'), 'utf-8');
                break;
        }
        // Look for word boundaries
        $search = mb_substr($string, 0, $max - $etcLength + 1, 'utf-8');
        if (preg_match('~[^\\w\\pL\\pN]~u', $search)) {
            // Boundary found
            $string = preg_replace('~[^\\w\\pL\\pN]*[\\w\\pL\\pN]*$~uU', '', $search);
        } else {
            // No word boundary found, will trim in the middle of a word
            $string = mb_substr($string, 0, $max - $etcLength, 'utf-8');
        }
        // Add "etc" at the end
        $string .= $etc;
        return $string;
    }

Usage Example

Esempio n. 1
0
 /**
  * Performs the test.
  *
  * @return \Jyxo\Beholder\Result
  */
 public function run() : \Jyxo\Beholder\Result
 {
     // The \GuzzleHttp library is required
     if (!class_exists(\GuzzleHttp\Client::class)) {
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::NOT_APPLICABLE, 'Guzzle library missing');
     }
     try {
         $httpClient = new \GuzzleHttp\Client();
         $httpRequest = new \GuzzleHttp\Psr7\Request('GET', $this->url, ['User-Agent' => 'JyxoBeholder']);
         $httpResponse = $httpClient->send($httpRequest, [\GuzzleHttp\RequestOptions::CONNECT_TIMEOUT => 5, \GuzzleHttp\RequestOptions::TIMEOUT => 10]);
         if (200 !== $httpResponse->getStatusCode()) {
             throw new \Exception(sprintf('Http error: %s', $httpResponse->getReasonPhrase()));
         }
         if (isset($this->tests['body'])) {
             $body = (string) $httpResponse->getBody();
             if (strpos($body, $this->tests['body']) === false) {
                 $body = trim(strip_tags($body));
                 throw new \Exception(sprintf('Invalid body: %s', \Jyxo\StringUtil::cut($body, 128)));
             }
         }
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::SUCCESS, $this->url);
     } catch (\Exception $e) {
         return new \Jyxo\Beholder\Result(\Jyxo\Beholder\Result::FAILURE, $e->getMessage());
     }
 }
All Usage Examples Of Jyxo\StringUtil::cut