Common character string functions in php (3) Replace str_replace () with substrings and phpstr_replace

Source: Internet
Author: User

Common character string functions in php (3) Replace str_replace () with substrings and phpstr_replace

MixedStr_replace(Mixed$search, Mixed$replace, Mixed$subject[, Int&$count]);

This function returns a string or array. This string or array issubjectAllsearchArereplaceResult After replacement.

Both the return value and the first three parameters can be strings or arrays. The fourth parameter specifies the number of replicas for a variable.

 

Example 1: All parameters are strings.

$bodytag  =  str_replace ( "%body%" ,  "black" ,  "<body text='%body%'>" );

=> "<Body text = 'black'>"

Example 2: parameter 1 is an array and 23 is a string.

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U", "P", "h");$onlyconsonants = str_replace($vowels, "@", "Hello world of php", $count);

=> "H @ ll @ w @ rld @ f p @ p" // The p in this example is not matched by P. This function isCase Sensitive. Use the str_ireplace () function to ignore case sensitivity.

=> $ Count => 5 // 5 times. E, o, h

Example 3:

$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";$order = array("\r\n", "\n", "\r");$replace = '<br/>';$newStr = str_replace($order, $replace, $str, $count);

=> $ Count => 4 // four times. \ N, \ r, \ r \ n, \ n, respectively. Note: Because \ r \ n is written in $ order, the Third matching is not divided into two \ r, \ n.

Example 4:

$letters  = array( 'a' ,  'p' );$fruit    = array( 'apple' ,  'pear' );$text     =  'a p' ;$output   =  str_replace ( $letters ,  $fruit ,  $text , $count);echo  $output ;echo  $count;

 

 

=> Guess what the output will be. Example 4 can be done. This function is enough.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.