Hướng dẫn
Quảng cáo

Hàm str-replace() trong PHP

Hướng dẫn cách sử dụng hàm str-replace() trong lập trình PHP

Tác dụng của hàm str-replace()

The str_replace() function replaces all occurrences of a string with another string.

This function is case-sensitive. For case-insensitive replacements, use the str_ireplace() function.

The following table summarizes the technical details of this function.

Return Value: Returns a string or an array with the replaced values.
Version: PHP 4+

Syntax

The basic syntax of the str_replace() function is given with:

str_replace(find, replace, string, count);

The following example shows the str_replace() function in action.

<?php
// Sample string
$str = "Twinkle Twinkle Little Star";

// Performing replacement
echo str_replace("Twinkle", "Shiny", $str);
?>

If find and replace are arrays, then str_replace() takes a value from each array and uses them to find and replace on string, as you can see in the following example:

<?php
// Sample string
$str  = "You should eat pizza, burger, and ice cream every day.";

// Defining find and replace arrays
$find   = array("pizza", "burger", "ice cream");
$replace = array("fruits", "vegetables", "grains");

// Performing replacement
echo str_replace($find, $replace, $str);
?>

If replace array has fewer values than the find array, then an empty string will be used for the rest of replacement values. Let's check out an example to understand how it works.

<?php
// Sample string
$str  = "The cookies and cake taste very good.";

// Defining find and replace arrays
$find   = array("cookies", "cake", "very");
$replace = array("tea", "coffee");

// Performing replacement
echo str_replace($find, $replace, $str);
?>

If find is an array and replace is a string, then the replace string will be used for every find value.

<?php
// Sample string
$str  = "Johny played and danced for hours.";

// Defining find array and replace string
$find   = array("played", "danced");
$replace = "slept";

// Performing replacement
echo str_replace($find, $replace, $str);
?>

Parameters

The str_replace() function accepts the following parameters.

Parameter Description
find Required. Specifies the value to find or search.
replace Required. Specifies the replacement value that replaces found values.
string Required. Specifies the string to be searched.
count Optional. Specifies a variable that will be set to the number of replacements performed.

More Examples

Here're some more examples showing how str_replace() function actually works:

The following example demonstrates how to find the number of replacements performed:

<?php
// Sample string
$str = "Rain Rain Go Away";

// Performing replacement
str_replace("Rain", "Sun", $str, $count);
echo "Number of replacements performed: $count";
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements