새 줄 바꿈을 감지하는 데 \ n 사용 하시겠습니까? 일부 시스템에서는 \ n, 다른 \ r \ n 및 다른 \ r을 사용하지만 \ n이 가장 일반적이라는 것을 알고 있습니다.
데이터의 출처에 따라 다릅니다. 운영 체제에 따라 줄 바꿈이 다릅니다.
Windows는을 사용하고 * nix (Mac OS 포함)은 \n
을 사용하고 오래된 MAC은 \r
을 사용합니다. 데이터가 웹 (예 : 텍스트 영역)에서 오는 경우에는 항상 \r\n
이됩니다. 그게 뭔데요 the spec은 user agents should do입니다. 마지막 " (따옴표) 같은 HTML 엔티티가 있는지
때때로, 그것은 & 바와 같이 왼쪽이고, 따라서 유효 HTML 아니다. 이 문제를 어떻게 방지 할 수 있습니까?
텍스트를 자르기 전에 HTML 엔티티를 일반 텍스트로 다시 변환 할 수 있습니다. 필요에 따라 htmlspecialchars_decode()
또는 html_entity_decode
을 사용하십시오. 이제 엔티티를 깨뜨리지 않아도됩니다 (필요한 경우 다시 엔코딩하는 것을 잊지 마십시오).
또 다른 옵션은 하드 문자 제한이 아닌 공백 문자에서만 텍스트를 분리하는 것입니다. 이렇게하면 "요약"에 전체 단어 만 표시됩니다.
대부분의 문제를 처리해야하는 클래스를 만들었습니다. 데이터가 텍스트 영역에서 오는 경우 이미 언급 한 바와 같이 항상 \r\n
될 것입니다,하지만 난 다음 (테스트되지 않은) 같은 것을 함께했다 다른 바꿈을 구문 분석 할 수 있도록 :
class Preview
{
protected $maxCharacters;
protected $maxLines;
protected $encoding;
protected $lineBreaks;
public function __construct($maxCharacters = 500, $maxLines = 10, $encoding = 'UTF-8', array $lineBreaks = array("\r\n", "\r", "\n"))
{
$this->maxCharacters = $maxCharacters;
$this->maxLines = $maxLines;
$this->encoding = $encoding;
$this->lineBreaks = $lineBreaks;
}
public function makePreview($text)
{
$text = $this->normalizeLinebreaks($text);
// this prevents the breaking of the "e; etc
$text = html_entity_decode($text, ENT_QUOTES, $this->encoding);
$text = $this->limitLines($text);
if (mb_strlen($text, $this->encoding) > $this->maxCharacters) {
$text = $this->limitCharacters($text);
}
return html_entity_decode($text, ENT_QUOTES, $this->encoding);
}
protected function normalizeLinebreaks($text)
{
return str_replace($lineBreaks, "\n", $text);
}
protected function limitLines($text)
{
$lines = explode("\n", $text);
$limitedLines = array_slice($lines, 0, $this->maxLines);
return implode("\n", $limitedLines);
}
protected function limitCharacters($text)
{
return substr($text, 0, $this->maxCharacters);
}
}
$preview = new Preview();
echo $preview->makePreview('Some text which will be turned into a preview.');
여러분, 매우 완전한 답변을 주셔서 감사합니다. 미리보기 클래스에 대해 많은 것을 감사 드리며 완벽하게 작동합니다! – federicot