توابع str_replace() در PHP

مثال

جایگزینی کاراکتر "world" در رشته "Hello world!" با "Shanghai":

<?php
echo str_replace("world","Shanghai","Hello world!");
?>

Run Instance

تعریف و استفاده

توابع str_replace() با استفاده از کاراکترهای دیگر برخی از کاراکترهای رشته را جایگزین می‌کند (با توجه به حروف بزرگ و کوچک).

این تابع باید از قوانین زیر پیروی کند:

  • اگر رشته جستجو یک آرایه است، آنگاه آرایه را برمی‌گرداند.
  • اگر رشته جستجو یک آرایه است، آنگاه به هر عنصر آرایه جستجو و جایگزینی می‌کند.
  • اگر همزمان نیاز به جستجو و جایگزینی در یک آرایه دارید و تعداد عناصر جایگزین کمتر از تعداد عناصر پیدا شده است، عناصر اضافی با رشته خالی جایگزین می‌شوند
  • اگر جستجو در یک آرایه است و جایگزینی یک رشته است، رشته جایگزین به همه مقادیر پیدا شده اعمال می‌شود.

نکته:این تابع جستجو را با توجه به حروف بزرگ و کوچک انجام می‌دهد. لطفاً از str_ireplace() این تابع جستجو را بدون توجه به حروف بزرگ و کوچک انجام می‌دهد.

نکته:این تابع امنیت دوگانه دارد.

زبان

str_replace(find,replace,string,count)
Parameters Description
find Required. Specifies the value to be searched for.
replace Required. Specifies the replacement find The value of the value in
string Required. Specifies the string to be searched.
count Optional. Variable for counting the replacement number.

Technical Details

Return Value: Returns a string or array with the replacement value.
PHP Version: 4+
Update Log:

In PHP 5.0, a new count parameters.

Before PHP 4.3.3, the parameters of this function were find and replace Trouble will occur when all parameters are arrays, which will cause an empty find The index is not changed to the internal pointer replace It is ignored on an array. The new version will not have this problem.

Starting from PHP 4.0.5, most parameters can be an array.

More Examples

Example 1

Use with arrays count The str_replace() function of variables:

<?php
$arr = array("blue","red","green","yellow");
print_r(str_replace("red","pink",$arr,$i));
echo "Replacement count: $i";
?>

Run Instance

Example 2

Use the str_replace() function with fewer elements to be replaced than the elements found:

<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_replace($find,$replace,$arr));
?>

Run Instance