php 字串截取函數

來源:互聯網
上載者:User
 代碼如下 複製代碼
<?php
  //構造字串
  $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  echo "原字串:<b>".$str."</b><br>";
  //按各種方式進行截取
  $str1 = substr($str,5);
  echo "從第5個字元開始取至最後:".$str1."<br>";
  $str2 = substr($str,9,4);
  echo "從第9個字元開始取4個字元:".$str2."<br>";
  $str3 = substr($str,-5);
  echo "取倒數5個字元:".$str3."<br>";
  $str4 = substr($str,-8,4);
  echo "從倒數第8個字元開始向後取4個字元:".$str4."<br>";
  $str5 = substr($str,-8,-2);
  echo "從倒數第8個字元開始取到倒數第2個字元為止:".$str5."<br>";
 ?>

支援中英文混合截取。

 代碼如下 複製代碼

<?
/*
------------------------------------------------------
參數:
$str_cut    需要截斷的字串
$length     允許字串顯示的最大長度

程式功能:截取全形和半形(漢字和英文)混合的字串以避免亂碼
------------------------------------------------------
*/
function substr_cut($str_cut,$length)
{
    if (strlen($str_cut) > $length)
    {
        for($i=0; $i < $length; $i++)
        if (ord($str_cut[$i]) > 128)    $i++;
        $str_cut = substr($str_cut,0,$i)."..";
    }
    return $str_cut;
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.