(PHP 4, PHP 5)
str_replace — ×Ó×Ö·û´®Ìæ»»
¸Ãº¯Êý·µ»ØÒ»¸ö×Ö·û´®»òÕßÊý×é¡£¸Ã×Ö·û´®»òÊý×éÊǽ« 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
Note: Èç¹û±»Ö¸¶¨£¬ËüµÄÖµ½«±»ÉèÖÃΪÌæ»»·¢ÉúµÄ´ÎÊý¡£
¸Ãº¯Êý·µ»ØÌæ»»ºóµÄÊý×é»òÕß×Ö·û´®¡£
°æ±¾ | ˵Ã÷ |
---|---|
5.0.0 |
ÐÂÔö count ²ÎÊý¡£
|
4.3.3 |
º¯ÊýÐÐΪ¸Ä±ä¡£¾ÉµÄ°æ±¾ÖдæÔÚÒ»¸ö BUG ¡ª¡ª µ± search ºÍ
replace Á½¸ö²ÎÊý¶¼ÊÇÊý×éµÄʱºò£¬½«µ¼ÖÂ¿ÕµÄ search Ë÷Òý±»Ìø¹ý£¬µ«ÊÇȴûÓÐͬʱǰÒÆ replace ÄÚ²¿Ö¸Õë¡£¸Ã´íÎó·¢ÉúÔÚ PHP 4.3.3£¬ÈκÎÒÀÀµÓÚ´Ë BUG µÄ½Å±¾Ó¦¸ÃÏȳýÈ¥¿ÕµÄ²éÕÒÖµ£¬´Ó¶øÄ£ÄâÔʼµÄÐÐΪ¡£
|
4.0.5 | ´ó¶àÊý²ÎÊý¶¼¿ÉÒÔΪÊý×é¡£ |
Example #1 str_replace() »ù±¾·¶Àý
<?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;
?>
Example #2 ¿ÉÄÜµÄ str_replace() Ìæ»»·¶Àý
<?php
// Ì滻˳Ðò
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
// Ê×ÏÈÌæ»» \r\n ×Ö·û£¬Òò´ËËüÃDz»»á±»Á½´Îת»»
$newstr = str_replace($order, $replace, $str);
// Êä³ö F £¬ÒòΪ A ±» B Ìæ»»£¬B ÓÖ±» C Ìæ»»£¬ÒÔ´ËÀàÍÆ...
// ÓÉÓÚ´Ó×óµ½ÓÒÒÀ´ÎÌæ»»£¬×îÖÕ E ±» F Ìæ»»
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// Êä³ö: apearpearle pear
// ÓÉÓÚÉÏÃæÌáµ½µÄÔÒò
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
Note: ´Ëº¯Êý¿É°²È«ÓÃÓÚ¶þ½øÖƶÔÏó¡£
ÓÉÓÚ str_replace() µÄÌ滻ʱ´Ó×óµ½ÓÒÒÀ´Î½øÐеģ¬½øÐжàÖØÌæ»»µÄʱºò¿ÉÄÜ»áÌæ»»µô֮ǰ²åÈëµÄÖµ¡£²Î¼û¸ÃÎĵµµÄ·¶Àý¡£
Note:
¸Ãº¯ÊýÇø·Ö´óСд¡£Ê¹Óà str_ireplace() ¿ÉÒÔ½øÐв»Çø·Ö´óСдµÄÌæ»»¡£