How to implement replacement position in php

藏色散人
Release: 2023-03-17 16:20:01
Original
4911 people have browsed it

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.

How to implement replacement position in php

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("一二三四五","二");
?>
Copy after login

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";
?>
Copy after login

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,&#39;&#39;, $pos, $len); 
}
echo $sentence;
?>
Copy after login

The filtered result is:

和一起去家找
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template