PHP – 如何使用 iconv_substr() 函式擷取字串的一部分?
在 PHP 中,**iconv_substr()** 函式用於根據偏移量和長度引數擷取指定字串的一部分。假設我們有一個字串 **"helloWorld"**,我們想擷取並只顯示字串 **(llowo)**,那麼我們將使用從 2 到 5 的數字來選擇它。
語法
string iconv_substr(str $string, int $offset, int $length, str $encoding)
引數
**iconv_substr()** 接受四個引數:**$string**、**$offset**、**$length** 和 **$encoding**。
**$string−** $string 引數指定原始字串。
**$offset−** 如果 $offset 引數是非負數,則 **iconv_substr()** 函式從偏移字元開始擷取字串的選定部分,從零開始計數。如果它是負數,則 **iconv_substr()** 函式從距離字串末尾偏移字元的位置開始擷取部分。
**$length−** 如果給出 $length 引數並且它是正數,則其返回值將包含從偏移量開始的部分中最多 length 個字元。
**$encoding−** 如果 encoding 引數不存在或為空,則假設字串採用 **iconv.internal_encoding** 編碼。
返回值
**iconv_substr()** 函式返回由偏移量和長度引數指定的字串部分。如果字串短於偏移字元數,它將返回 False。如果字串的長度與偏移字元數完全相同,則將返回空字串。
示例 1
不帶空格的 iconv_substr() 函式
線上演示
<?php
// Helloworld sting is used
// To cut the selected portion from string
//iconv_substr function is used
$string = iconv_substr("HelloWorld!", 2, 7, "UTF-8");
// It will returns the character from 2 to 7
var_dump($string);
?>輸出
string(7) "lloWorl"
示例 2
帶空格的 iconv_substr() 函式
線上演示
<?php
// Helloworld sting is used
// To cut the selected portion from string
//iconv_substr function is used
$string = iconv_substr ("Hello World!", 2, 7, "UTF-8");
// It will returns the character from 2 to 7
var_dump($string);
?gt;輸出
string(7) "llo Wor"
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP