str_replace() - 子字符串替换 - php 字符串函数
str_replace()
(PHP 4, PHP 5, PHP 7)
子字符串替换
说明
str_replace(mixed $search, mixed $replace, mixed $subject[,int &$count] ): mixed该函数返回一个字符串或者数组。该字符串或数组是将$subject中全部的$search都被$replace替换之后的结果。
如果没有一些特殊的替换需求(比如正则表达式),你应该使用该函数替换ereg_replace()和preg_replace()。
参数
如果$search和$replace为数组,那么str_replace()将对$subject做二者的映射替换。如果$replace的值的个数少于$search的个数,多余的替换将使用空字符串来进行。如果$search是一个数组而$replace是一个字符串,那么$search中每个元素的替换将始终使用这个字符串。该转换不会改变大小写。
如果$search和$replace都是数组,它们的值将会被依次处理。
$search查找的目标值,也就是needle。一个数组可以指定多个目标。
$replace$search的替换值。一个数组可以被用来指定多重替换。
$subject执行替换的数组或者字符串。也就是haystack。
如果$subject是一个数组,替换操作将遍历整个$subject,返回值也将是一个数组。
$count如果被指定,它的值将被设置为替换发生的次数。
返回值
该函数返回替换后的数组或者字符串。
范例
Example #1str_replace()基本范例
Enjoy
$myString = “It was the best of mine it was the worst of mine,”; // Displays “It was the best of bananas, it was the worst of bananas,” echo str_replace( “mine”, “bananas”, $myString ); If you want to know how many times the search string was replaced, pass in a variable as an optional fourth argument. After the function runs, this variable holds the number of replacements: $myString = “It was the best of mine, it was the worst of mine,”; // Displays “It was the best of bananas, it was the worst of bananas,” echo str_replace( “mine”, “bananas”, $myString, $num ) . “ ”; // Displays “The text was replaced 2 times.” echo “The text was replaced $num times. ”;
I was working with MySQL and displaying the title to things on the web page. I'd written a script to ensure single and double quotes were removed from the title. I used $title = str_replace( "'", "", $title ); and $title = str_replace( '"', "", $title ); But still the single and double quotes continued. So I wrote a bit of code to print out each character separated by a dash. Like so: for( $i=0; $i
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)