Home  >  Article  >  Backend Development  >  How to swap substring positions in php

How to swap substring positions in php

*文
*文Original
2018-01-02 11:09:532511browse

How does php realize the swapping of substring positions? This article mainly introduces the method of swapping and exchanging substring positions in PHP. It can realize the function of exchanging two substrings in a simple string. It involves PHP string operations, insertion, replacement and other related skills. Friends who need it You can refer to it. I hope to be helpful.

The details are as follows:

<?php
/*子字符串位置互换
 */
$str1="Tom";
$str2="Jack";
$str="This is an example,you see Tom tell Jack something";
function str_change($str,$str1,$str2){
  $len1=strlen($str1);
  $len2=strlen($str2);
  $pos1=strpos($str,$str1);
  $str=substr_replace($str,$str2,$pos1,$len1);//替换$str1为$str2
  $pos2= strpos($str,$str2,$len1+$pos1);//定位替换后字符串中原$str2字段的位置
  return substr_replace($str,$str1,$pos2,$len2);//替换$str2为$str1
}
echo str_change($str,$str1,$str2);
?>

The running result is:

This is an example, you see Jack tell Tom something

Related recommendations:

php Related functions for string escaping

php String splitting Introduction to and comparison

php Detailed explanation of the use of string regular replacement function preg_replace

The above is the detailed content of How to swap substring positions 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