PHP str_replace() συνάρτηση

Παράδειγμα

Αντικατάσταση του χαρακτήρα "world" στην αλυσίδα κειμένων "Hello world!" με "Shanghai":

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

Run Instances

Ορισμός και χρήση

Η συνάρτηση 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 of the value of the value.
string Required. Specifies the string to be searched.
count Optional. Variable for counting the replacement numbers.

Technical Details

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

In PHP 5.0, a new count parameters.

Before PHP 4.3.3, the function's find and replace Troubles will occur when all parameters are arrays, causing empty find The index is not changed to the internal pointer replace It is ignored on arrays. New versions 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 Instances

Example 2

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

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

Run Instances