Javascript 在php上截断每个单词中的字符

Javascript 在php上截断每个单词中的字符,javascript,php,web,Javascript,Php,Web,我需要在每个单词中不超过25个字符。是的,我可以使用break-word:break-all,但是,我不喜欢它对长单词的处理方式。 我编写了一个JavaScript函数,它按字母截断这些单词并添加分隔符。你能建议一个更好的选择或者用php重写这个程序吗,因为我还不太懂php if(document.getElementById('title\u parent')&&document.getElementById('title')){ document.getElementById('title

我需要在每个单词中不超过25个字符。是的,我可以使用break-word:break-all,但是,我不喜欢它对长单词的处理方式。 我编写了一个JavaScript函数,它按字母截断这些单词并添加分隔符。你能建议一个更好的选择或者用php重写这个程序吗,因为我还不太懂php

if(document.getElementById('title\u parent')&&document.getElementById('title')){
document.getElementById('title')。oninput=function(){
const parent=document.getElementsByClassName('edit-project-title')[0];
parent.innerHTML=this.value?truncate(this.value,20'…'):“”;
}
}
函数截断(str、maxWordLength、endLetters){
如果(“字符串”!==str的类型){
返回“”;
}
const words=str.split(/\s+/g);
常量completedWords=[];
为了(让一个字一个字){
如果(word.length>maxWordLength)
completedWords.push(word.slice(0,maxWordLength+1)+结束字母);
其他的
完成单词。推(单词);
}

返回completedWords.join(“”)。替换(/\尝试用PHP重写JavaScript函数。有关详细说明,请参阅注释

输出:
这里有一些简短的单词和一个非常长的单词>现在:pneumoultramicrosco…

<?php

// Set some default values for max word length and end letters arguments.
// If you pass these, your paremeter values will be used.
function truncate(string $input, int $maxWordLength = 20, string $endLetters = '...')
{
    // No manual type checking required if you use declare(strict_types=1),
    // in combination with type hinting in the argument list.
    
    // foreach() replaces for ... of
    // preg_split() replaces String.prototype.split()
    foreach (preg_split('/\s+/', $input) as $word)
    {
        // strlen() replaces .length
        if (strlen($word) > $maxWordLength)
            // substr() replaces String.prototype.slice()
            $completedWords[] = substr($word, 0, $maxWordLength + 1) . $endLetters;
        else
            $completedWords[] = $word;
    }

    // implode() replaces .join()
    // str_replace() replaces .replace()
    return str_replace('<', '&lt;', implode(' ', $completedWords));
}

$input = 'here are some short words and a <really long one> now: pneumonoultramicroscopicsilicovolcanoconiosis';

echo truncate($input);

谢谢,这是我见过的最好的解释。顺便问一下,我想知道为什么给我-1