PHP substr_replace()函數的幾個應用例子_PHP教程

來源:互聯網
上載者:User

substr_replace()函數介紹

substr_replace() 函數把字串的一部分替換為另一個字串。

文法:substr_replace(string,replacement,start,length)

  • 參數string,必需。規定要檢查的字串。
  • 參數replacement,必需。規定要插入的字串。
  • 參數start,必需。規定在字串的何處開始替換。正數 - 在第 start 個位移量開始替換;負數 - 在從字串結尾的第 start 個位移量開始替換;0 - 在字串中的第一個字元處開始替換。
  • 參數charlist,可選。規定要替換多少個字元。正數 - 被替換的字串長度;負數 - 從字串末端開始的被替換字元數;0 - 插入而非替換。

如果 start 是負數且 length 小於等於 start,則 length 為 0。

Program List:substr_replace()函數基本用法

    \n";/* These two examples replace all of $var with 'bob'. */echo substr_replace($var, 'bob', 0) . "
\n";echo substr_replace($var, 'bob', 0, strlen($var)) . "
\n";/* Insert 'bob' right at the beginning of $var. */echo substr_replace($var, 'bob', 0, 0) . "
\n";/* These next two replace 'MNRPQR' in $var with 'bob'. */echo substr_replace($var, 'bob', 10, -1) . "
\n";echo substr_replace($var, 'bob', -7, -1) . "
\n";/* Delete 'MNRPQR' from $var. */echo substr_replace($var, '', 10, -1) . "
\n";?>

程式運行結果:

Original: ABCDEFGH:/MNRPQR/bobbobbobABCDEFGH:/MNRPQR/ABCDEFGH:/bob/ABCDEFGH:/bob/ABCDEFGH://

Program List:將過長的字串用省略符號代替一部分

下面的程式可以將過長的字串保留首尾,中間用省略符號代替。

    

程式運行結果:

abcdefghijk...456789z.jpg

Program List:將多出的字元用省略符號代替

   $numb) {$text = substr($text, 0, $numb);$text = substr($text,0,strrpos($text," "));    //This strips the full stop:    if ((substr($text, -1)) == ".") {        $text = substr($text,0,(strrpos($text,".")));    }$etc = "..."; $text = $text.$etc;} $text = htmlentities($text, ENT_QUOTES); return $text;}//Call function$text = 'welcome to bkjia, welcome to bkjia, welcome to bkjia';$result = truncate($text, 35);echo $result;?>

程式運行結果:

welcome to bkjia, welcome to...

Program List:給金錢數額加上逗號

  

程式運行結果:

163,000

http://www.bkjia.com/PHPjc/752379.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752379.htmlTechArticlesubstr_replace()函數介紹 substr_replace() 函數把字串的一部分替換為另一個字串。 文法:substr_replace(string,replacement,start,length) 參數string,必...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.