/** * Create an extract from a text, so if the search-string was found, it will be centered in the output. * * @param string $search * @param int|null $length * @param string $ellipsis * * @return Stringy */ public function extractText($search = '', $length = null, $ellipsis = '...') { // init $text = $this->str; if (empty($text)) { return static::create('', $this->encoding); } $trimChars = "\t\r\n -_()!~?=+/*\\,.:;\"'[]{}`&"; if ($length === null) { $length = $this->length() / 2; } if (empty($search)) { $stringLength = UTF8::strlen($text, $this->encoding); $end = $length - 1 > $stringLength ? $stringLength : $length - 1; $pos = min(UTF8::strpos($text, ' ', $end, 0, $this->encoding), UTF8::strpos($text, '.', $end)); if ($pos) { return static::create(rtrim(UTF8::substr($text, 0, $pos, $this->encoding), $trimChars) . $ellipsis, $this->encoding); } else { return static::create($text, $this->encoding); } } $wordPos = UTF8::strpos(UTF8::strtolower($text), UTF8::strtolower($search, $this->encoding), null, $this->encoding); $halfSide = (int) ($wordPos - $length / 2 + UTF8::strlen($search, $this->encoding) / 2); if ($halfSide > 0) { $halfText = UTF8::substr($text, 0, $halfSide, $this->encoding); $pos_start = max(UTF8::strrpos($halfText, ' ', 0), UTF8::strrpos($halfText, '.', 0)); if (!$pos_start) { $pos_start = 0; } } else { $pos_start = 0; } if ($wordPos && $halfSide > 0) { $l = $pos_start + $length - 1; $realLength = UTF8::strlen($text, $this->encoding); if ($l > $realLength) { $l = $realLength; } $pos_end = min(UTF8::strpos($text, ' ', $l, $this->encoding), UTF8::strpos($text, '.', $l, $this->encoding)) - $pos_start; if (!$pos_end || $pos_end <= 0) { $extract = $ellipsis . ltrim(UTF8::substr($text, $pos_start, UTF8::strlen($text), $this->encoding), $trimChars); } else { $extract = $ellipsis . trim(UTF8::substr($text, $pos_start, $pos_end, $this->encoding), $trimChars) . $ellipsis; } } else { $l = $length - 1; $trueLength = UTF8::strlen($text, $this->encoding); if ($l > $trueLength) { $l = $trueLength; } $pos_end = min(UTF8::strpos($text, ' ', $l, $this->encoding), UTF8::strpos($text, '.', $l, $this->encoding)); if ($pos_end) { $extract = rtrim(UTF8::substr($text, 0, $pos_end, $this->encoding), $trimChars) . $ellipsis; } else { $extract = $text; } } return static::create($extract, $this->encoding); }