2016-07-29 53 views
0

我想用具體條件替換文件中的內容。 實施例:從具有特定條件的文件中替換內容

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_replace或者一個函數來實現這種功能y其他功能。

回答

1

您可以使用word boundaries\b)確保短語不是另一個詞的子部分。例如

\bla\b 

會發現la,與i修改它將搜索不區分大小寫。

正則表達式演示:https://regex101.com/r/bX9rD4/2

PHP用法:

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

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

+0

偉大它的工作完美..謝謝so..much哥哥的快速解決方案:) – Bhavin