Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
文字列が指定された長さを超えていないかどうかを確認する必要がある状況では、切り捨てて省略記号を追加します
function truncate($str, $length){ if (strLen($str) > $length) { $str = substr($str, 0, $length) . ' ...'; } return $str; }
インラインで次の場合:
return strLen($str) > $length ? substr($str, 0, $length) . ' ...' : $str;
正規表現ソリューションを探している場合:
function truncate($str, $length) { return preg_replace('/(.{'.(int)$length.'}).+/s', '$1 ...', $str); }