Summary of various usages of str_replace functions in PHP

Source: Internet
Author: User
Function prototypes: Mixed str_replace (mixed $search, mixed $replace, mixed $subject [, int & $count])

The three parameter types of this function are mixed, so they can both be strings or arrays, so there are several uses:

1, $search and $replace are strings, which is the most common usage

Echo Str_replace ("A", "Apple", "This is a demo.");

Output: This is Apple demo.


2, $search An array, the elements in $search are replaced by $replace, and the final output is a string.

echo str_replace (Array ("A", "P", "O"), "Apple", "This is a demo.");

Output: This is a apple Apple le demApple.


3, $replace an array, will be error and will not output the expected results, do not recommend the use of

Echo Str_replace ("A",  array ("Apple", "pear"), "This is a demo.");

Output: This is Array demo. and error Notice:array to string conversion


4, $subject an array, each element in the $subject is replaced by an independent one, and the final output is a group.

Print_r (Str_replace ("A", "Apple", Array ("This is a demo.", "the" This is not a demo. ")));

Output: Array ([0] = = Apple demo. [1] = = This isn't Apple demo. )


5, $search and $replace are an array, then can be divided into three kinds of situations:

a). $search as long as the $replace, the same subscript corresponds to the replacement

b). $search longer than $replace, the array elements that are more than $replace in $search are replaced with empty strings

c). $search shorter than $replace, the array elements in the $replace are ignored

echo str_replace (Array ("A", "O"), Array ("Apple", "pear"), "This is a demo.");

Output: This is apple dempear.


6, $search, $replace and $subject are all arrays, which is a combination of the above

Print_r (Str_replace (Array ("A", "O"), Array ("Apple", "pear"), Array ("This is a demo.", "Here is a demo."));

Output: Array ([0] = = Apple dempear. [1] = = This is npeart Apple dempear. )

  • 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.