replace()
用第三個表達式替換第一個字符串表達式中出現的所有第二個給定字符串表達式。
語法
REPLACE ( 'string_expression1' , 'string_expression2' , 'string_expression3' )
REPLACE ( '要修改的總體數據' , '被替換的內容' , '要替換的內容' )
參數
'string_expression1'
待搜索的字符串表達式。string_expression1 可以是字符數據或二進制數據。
'string_expression2'
待查找的字符串表達式。string_expression2 可以是字符數據或二進制數據。
'string_expression3'
替換用的字符串表達式。string_expression3 可以是字符數據或二進制數據。
返回類型
如果 string_expression(1、2 或 3)是支持的字符數據類型之一,則返回字符數據。如果 string_expression(1、2 或 3)是支持的 binary 數據類型之一,則返回二進制數據。
示例
下例用 xxx 替換 abcdefghi 中的字符串 cde。
SELECT REPLACE('abcdefghicde','cde','xxx') GO
下面是結果集:
------------ abxxxfghixxx (1 row(s) affected)
-
search -
查找的目標值,也就是 needle。一個數組可以指定多個目標。
-
replace -
search的替換值。一個數組可以被用來指定多重替換。 -
subject -
執行替換的數組或者字符串。也就是 haystack。
如果
subject是一個數組,替換操作將遍歷整個subject,返回值也將是一個數組。 -
count -
如果被指定,它的值將被設置為替換發生的次數。
示例:
<?php
// 賦值: <body text='black'>
$bodytag = str_replace ( "%body%" , "black" , "<body text='%body%'>" );
// 賦值: Hll Wrld f PHP
$vowels = array( "a" , "e" , "i" , "o" , "u" , "A" , "E" , "I" , "O" , "U" );
$onlyconsonants = str_replace ( $vowels , "" , "Hello World of PHP" );
// 賦值: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day." ;
$healthy = array( "fruits" , "vegetables" , "fiber" );
$yummy = array( "pizza" , "beer" , "ice cream" );
$newphrase = str_replace ( $healthy , $yummy , $phrase );
// 賦值: 2
$str = str_replace ( "ll" , "" , "good golly miss molly!" , $count );
echo $count ;
?>
