php str_replice_PHP str_replace() 函数的常见用法

/*Function:

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

*/

//1==>

// 输出:

/*

这应该是最常见的用法了,从"

"中找到"%body%",然后替换成"black"

*/

$bodytag = str_replace("%body%", "black", "

");

//2==>

// 输出: Hll Wrld f PHP

/*

参数 search 为数组的用法,逐个地遍历数组来进行替换

*/

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");

$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

//3==>

// 输出: You should eat pizza, beer, and ice cream every day

/*

参数 search 和 replace 均为数组的用法,且数组元素的个数相同,进行相互对应的替换

*/

$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);

//4==>

// Use of the count parameter is available as of PHP 5.0.0

/*

输出匹配次数

*/

$str = str_replace("ll", "", "good golly miss molly!", $count);

echo $count; // 2

//5==>

// Order of replacement

/*

自定义替换顺序,防止重复替换

*/

$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";

$order = array("\r\n", "\n", "\r");

$replace = '
';

// Processes \r\n's first so they aren't converted twice.

$newstr = str_replace($order, $replace, $str);

//6==>

/*

这个是需要注意的,参数 search 和 replace 均为数组,第一次先替换 'a' ,结果为 'apple p',第二次接着替换 'p',因此会出现结果 'apearpearle pear'

*/

// Outputs: apearpearle pear

$letters = array('a', 'p');

$fruit = array('apple', 'pear');

$text = 'a p';

$output = str_replace($letters, $fruit, $text);

echo $output;

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值