2016-07-29 2 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 또는 다른 기능들.

답변

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

관련 문제