Two php string replacement functions

Source: Internet
Author: User
Tags function prototype mixed

This article mainly introduces two php string replacement functions: str_replace and substr_replace. The former is to replace needle in all haystace and return the result after replacement of haystace, the specific part of the string to be replaced by substr_replace depends on the start position and the value of the optional parameter length.
Str_replace ()

Function prototype:

Mixed str_replace (mixed needle, mixed new_needle, mixed haystace [, int & count])

The function replaces needle in all haystace with new_needle, and returns the result after replacement with haystace. The fourth optional parameter, count, contains the number of replacement operations to be performed.

Example:

The code is as follows: Copy code
<? Php
Function n2n (){
= Array ('1', '2', '3', '4', '5', '6', '7', '8', '9 ', '0 ');
= Array ("7", "8", "9", "0", "1", "2", "3", "4", "5 ", "6 ");
= Strlen ();
For (= 0; <; ++ ){
For (= 0; <10; ++)
If (= ){
= Str_replace (,,);
Break;
  }
   }
Return;
  }
 
= "1234abc56 ";
Echo n2n ();
 
?>



The substr_replace () function is used to find and replace a specific substring in the string at a given position. Prototype:

String substr_replace (string, string replacement, int start, int [length]);

The code is as follows: Copy code
<? Php
Echo substr_replace ("hello world", "earth", 6); // hello earth
?>


 
Negative
 

The code is as follows: Copy code
<? Php
Substr_replace ('huevos ', 'X',-2,-2); // huevxos
Substr_replace ('huevos ', 'X',-2,-3); // huevxos
Substr_replace ('huevos ', 'X',-2,-3); // huevxos
?>



The function uses the string replacement to replace a part of a string. The specific part depends on the start position and the value of the optional parameter length.

The start value indicates the start offset of the string to be replaced. If it is 0 or a positive value, it is the offset calculated from the start of the string. If it is a negative value, it is

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.