Home  >  Article  >  Backend Development  >  How to replace string in string in php

How to replace string in string in php

藏色散人
藏色散人Original
2020-07-04 09:22:274628browse

php method to replace strings in strings: first create a PHP sample file; then enter the code "str_replace("world","Shanghai","Hello world!");"; and finally execute the Just file.

How to replace string in string in php

php replaces the string in the string

You can use the str_replace() function.

Definition and Usage

str_replace() function replaces some characters in a string with other characters (case sensitive).

This function must follow the following rules:

If the searched string is an array, then it will return an array.

If the searched string is an array, then it will find and replace each element in the array.

If you need to search and replace the array at the same time, and the elements that need to be replaced are less than the number of found elements, then the excess elements will be replaced with empty strings

If the searched is an array, and the replacement is a string, then the replacement string will work on all found values.

Note: This function is case-sensitive. Please use the str_ireplace() function to perform a case-insensitive search.

Note: This function is binary safe.

Syntax

str_replace(find,replace,string,count)

Parameters

find Required. Specifies the value to look for.

replace Required. Specifies the value to replace the value in find.

string Required. Specifies the string to be searched for.

count Optional. Variable counting the number of substitutions.

Technical details

Return value: Returns a string or array with the replacement value.

PHP version: 4

Change log:

In PHP 5.0, the count parameter is added.

Before PHP 4.3.3, trouble would be encountered when both the find and replace parameters of this function were arrays, which would cause the empty find index to be ignored when the internal pointer was not replaced on the replace array. The new version won't have this problem.

Since PHP 4.0.5, most parameters can be an array.

Example

Replace the character "world" in the string "Hello world!" with "Shanghai":

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

Run

Hello Shanghai!

More For relevant knowledge, please visit PHP中文网!

The above is the detailed content of How to replace string in string in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn