Click here to Skip to main content
15,890,845 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi i have a txt file and i want to use php to make some changes

example.:
var="Test need to change"

I want to find string Test and change the rest of sentence

when finish it sould be
var="Test changed text".


What I have tried:

Replace string in file using PHP and preg_replace function
Posted
Updated 26-Jan-17 2:16am
v2
Comments
Patrice T 26-Jan-17 6:51am    
Did you try something ?
What is the question ?
kdaras 26-Jan-17 7:10am    
I have try preg_replace('/(pattern)X*/', $_POST['name'], $file_contents) but
this is the opposite of what i'm asking

You need to use a back reference to include the matched string in the result:
PHP
<?php
$string = 'Test need to change';
$pattern = '/(Test).*/';
$insert = 'changed text';
$replacement = "$1 $insert";
echo preg_replace($pattern, $replacement, $string);
?>
 
Share this answer
 
 
Share this answer
 
Comments
kdaras 26-Jan-17 7:09am    
I have seen PHP: str_replace - Manual[^] but i didn't find an example of what i'm asking
Richard MacCutchan 26-Jan-17 7:35am    
Try using substr or substr_replace. It is not clear where your problem lies in doing what is a very simple replacement.
kdaras 26-Jan-17 7:45am    
in the sentence "Test some kind o text " i want to find string Test
and change the rest of sentence leaving Test string as it is.
Richard MacCutchan 26-Jan-17 7:53am    
There is an example of a similar replacement method on the preg_replace manual page.
OK i find the solution thanks for help
preg_replace('/(pattern)X*.*/', $_POST['name'], $file_contents) but
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900