php提供多種字符串截取函數(shù):substr():截取字符串指定部分。substring():從字符串末尾向起始位置截取子字符串。substr_replace():替換字符串指定部分。str_replace():替換字符串指定部分為其他部分。
PHP 中截取字符串的函數(shù)
PHP 提供了多種函數(shù)來截取字符串,其中最常用的包括:
substr(): 將字符串的一部分(子字符串)截取并返回。其語法為:substr(string $string, int $start, int $length = null),其中 $start 指定子字符串的起始位置,$length 指定子字符串的長度。
例如:
<code class="php">$string = "Hello World!"; $substring = substr($string, 0, 5); // "Hello"</code>
登錄后復(fù)制
substring(): 功能與 substr() 類似,但從字符串末尾向起始位置截取子字符串。其語法為:substring(string $string, int $start, int $length = null),其中 $start 指定子字符串的起始位置,$length 指定子字符串的長度。
例如:
<code class="php">$string = "Hello World!"; $substring = substring($string, 10, 5); // "World"</code>
登錄后復(fù)制
substr_replace(): 用指定字符串替換字符串中的一部分。其語法為:substr_replace(string $string, string $replacement, int $start, int $length = null),其中 $start 指定替換的起始位置,$length 指定替換的長度。
例如:
<code class="php">$string = "Hello World!"; $substring = substr_replace($string, "there", 7, 5); // "Hello there!"</code>
登錄后復(fù)制
str_replace(): 將字符串中的某些部分替換為其他部分。其語法為:str_replace(mixed $search, mixed $replace, mixed $subject),其中 $search 指定要替換的部分,$replace 指定替換后的部分,$subject 指定目標(biāo)字符串。
例如:
<code class="php">$string = "Hello World!"; $substring = str_replace("World", "there", $string); // "Hello there!"</code>
登錄后復(fù)制