首頁  >  文章  >  後端開發  >  php替換表達式怎麼寫

php替換表達式怎麼寫

藏色散人
藏色散人原創
2021-12-17 09:26:472347瀏覽

php替換表達式的寫法有:1、「str_ireplace($search, $replace, $str);」方式;2、「substr_replace($str, $replace, 0,5);」方式。

php替換表達式怎麼寫

本文操作環境:Windows7系統,PHP7.1版,Dell G3電腦。

php替換表達式怎麼寫?

PHP字串替換

在PHP 中,可以對一個字串中的特定字元或子字串進行替換,這是非常常用的功能。

str_ireplace() 和str_replace() 函數

str_ireplace() 和str_replace 使用新的字串取代原來字串中指定的特定字串,str_replace 區分大小寫,str_ireplace() 不區分大小寫,兩者語法相似。

str_ireplace() 的語法如下:

mixed str_ireplace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

此函數傳回字串或陣列。該字串或陣列是將 subject 中全部的 search 以 replace 取代(忽略大小寫)之後的結果。參數 count 表示執行替換的次數。

使用範例如下:

<?php
$str = &#39;hello,world,hello,world&#39;;
$replace = &#39;hi&#39;;
$search = &#39;hello&#39;;
echo str_ireplace($search, $replace, $str);
?>

執行上述程式碼的輸出結果為:

hi,world,hi,world

substr_replace() 函數

substr_replace( ) 函數的語法如下:

mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )

substr_replace() 在字串string 的副本中將由start 和可選的length 參數限定的子字串使用replacement 進行替換。

如果 start 為正數,替換將從 string 的 start 位置開始。如果 start 為負數,替換將從 string 的倒數第 start 個位置開始。

如果設定了 length 參數且為正數,就表示 string 中被替換的子字串的長度。如果設定為負數,就表示待替換的子字串結尾處距離 string 末端的字元個數。如果沒有提供此參數,那麼預設為 strlen(string)(字串的長度)。當然,如果 length 為 0,那麼這個函數的函數為將 replacement 插入 string 的 start 位置處。

此函數的使用範例如下:

<?php
$str = &#39;hello,world,hello,world&#39;;
$replace = &#39;hi&#39;;
echo substr_replace($str, $replace, 0,5);
?>

以上程式碼的執行結果為:

hi,world,hello,world

推薦學習:《PHP影片教學

以上是php替換表達式怎麼寫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn