PHP提供多種字串截取函數:substr():截取字串指定部分。 substring():從字串結尾向起始位置截取子字串。 substr_replace():替換字串指定部分。 str_replace():替換字串指定部分為其他部分。
![php中截取字串的函數是什麼](https://img.php.cn/upload/article/202404/29/2024042912423180879.jpg)
PHP 中截取字串的函數
PHP 提供了多種函數來截取字串,其中最常用的包括:
-
substr(): 將字串的一部分(子字串)截取並傳回。其語法為:substr(string $string, int $start, int $length = null),其中 $start 指定子字串的起始位置,$length 指定子字串的長度。
例如:
$string = "Hello World!";
$substring = substr($string, 0, 5); // "Hello"
登入後複製
- substring(): 功能與substr() 類似,但從字串末尾向起始位置截取子字符串。其語法為:substring(string $string, int $start, int $length = null),其中 $start 指定子字串的起始位置,$length 指定子字串的長度。
例如:
$string = "Hello World!";
$substring = substring($string, 10, 5); // "World"
登入後複製
- substr_replace(): 以指定字串取代字串中的一部分。其語法為:substr_replace(string $string, string $replacement, int $start, int $length = null),其中 $start 指定替換的起始位置,$length 指定替換的長度。
例如:
$string = "Hello World!";
$substring = substr_replace($string, "there", 7, 5); // "Hello there!"
登入後複製
- str_replace(): 將字串中的某些部分替換為其他部分。其語法為:str_replace(mixed $search, mixed $replace, mixed $subject),其中 $search 指定要替換的部分,$replace 指定替換後的部分,$subject 指定目標字串。
例如:
$string = "Hello World!";
$substring = str_replace("World", "there", $string); // "Hello there!"
登入後複製
以上是php中截取字串的函數是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!