php method to implement replacement position: 1. Create a php sample file; 2. Use the strpos function to find whether a string contains a certain phrase; 3. Use the substr_replace function to achieve replacement.
The operating environment of this tutorial: Windows 10 system, PHP version 8.1, Dell G3 computer.
php How to achieve replacement position?
Find and replace Chinese strings in PHP
Find whether a string contains a certain phrase
<?php echo strpos("一二三四五","一"); echo "<br>"; echo strpos("一二三四五","二"); ?>
The printed result is:
0
3
The following is the code to replace a certain word:
<?php $word = "一二三四五"; $reWord = "六六六"; $pos = strpos("一二三四五","三"); $newWord = substr_replace($word, $reWord, $pos, 3);//从上面的例子中可以看出中文是占3个字符,所以最后一个参数为3 //要想得到(一二六六六 )的结果,就相当于替换掉后面的3个中文,可以把最后一个参数改为3*3即9 //如果最后一个参数为0就可以实现在制定下标上插入新字符串 echo "$newWord"; ?>
The output result is:
一二六六六四五
Use string replacement to filter text
<?php $words = ["我", "你", "他", "她"];//过滤库 $sentence = "我和你一起去他家找她";//待过滤的句子 foreach($words as $word)//遍历过滤库的词 { $len = strlen($word);//获取过滤词的长度 $pos = strpos($sentence,$word);//寻找过滤词的位置 $sentence = substr_replace($sentence,'', $pos, $len); } echo $sentence; ?>
The filtered result is:
和一起去家找
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to implement replacement position in php. For more information, please follow other related articles on the PHP Chinese website!