用一個 PHP 中以 “…” 主體的字串縮短字串?


假設我們的字串如下 -

$sentence="This is my first PHP program";

我們想要以下輸出 -

This is my first PHP ... gram

我們使用 “…” 縮短字串。為此,請使用 substring() 的概念,並透過檢查單詞數量來設定條件 -

示例

 即時演示

<!DOCTYPE html>
<html>
<body>
<?php
$sentence="This is my first PHP program";
if (strlen($sentence) >= 13) {
    echo substr($sentence, 0, 20). " ... " . substr($sentence, -4);
} else {
    echo $sentence;
}
?>
</body>
</html>

輸出

This is my first PHP ... gram

更新於:2020-10-12

145 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.