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
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!