用特定条件替换文件中的内容



我想用特定条件替换文件中的内容。示例:

if we have to replace LA to SF .     
if we have lable (after LA characters ) - No replace
if we have LA (after that one space ) - replace
if we have LA. (after that one dot) -  replace 

PHP代码:

<?php
    if(isset($_POST['search']) && isset($_POST['replace']))
    {
            $search = trim($_POST['search']);
            $replace = trim($_POST['replace']);
            $filename = 'lorem.txt';
            $text_content = file_get_contents($filename);
            $contents = str_replace($search,$replace,$text_content,$count);
            $modified_content = file_put_contents($filename,$contents);
    }
?>

HTML代码:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form method="post" action="">
<input type="text" name="search" />
<input type="text" name="replace" />
<button type="submit"> Replace </button>
</body>
</html>
?>

我试过使用preg_replace,但我有两个词,一个是搜索,另一个是替换所以如何使用preg_repace或任何其他函数来实现这种功能。

您可以使用单词边界(b)来确保一个短语不是另一个单词的子部分。例如

blab

将查找la,使用i修饰符将搜索不区分大小写。

Regex演示:https://regex101.com/r/bX9rD4/2

PHP用法:

$strings='if we have lable 
if we have LA 
if we have LA.';
echo preg_replace('/blab/i', 'SF', $strings);

PHP演示:https://eval.in/613972

最新更新