2016-07-29 10 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を試みたが、私は2つの単語検索で2つ目は、あるものを持っていますを置き換えて、この種の機能をpreg_replaceまたはその他の関数。

答えて

1

フレーズが別の単語のサブ部分でないことを確認するには、word boundaries\b)を使用できます。例

\bla\b 

のために、それは大文字小文字を区別しない検索しますi修飾子で、laがあります。

正規表現のデモ: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

関連する問題