How to delete text from a file using preg_replace() function in PHP?

Configurare noua (How To)

Situatie

preg_replace( $pattern, $replacement, $subject);
Parameters:

$pattern: It contains the string we have to replace.
$replacement: It contains the string that will replace the existing string.
$subject: It contains the main string file where need to remove the string.
We have created a text file named as fruits.txt

mango
apple
papaya
guava
apple
grapes
mango
apple

This program removes all the strings from the given file.

Solutie

Pasi de urmat

 

<?php

$a = ‘fruits.txt’;
$b = file_get_contents(‘fruits.txt’);
echo “File contents before using ”
. “preg_replace() function<br>”;
echo $b;
echo “<br><br>File contents after using ”
. “preg_replace() function<br> “;
$c = preg_replace(‘/[a-z]/’, ”, $b);
echo $c;
file_put_contents($a, $c);
?>

 

Output:

File contents before using preg_replace() function
mango apple papaya guava apple grapes mango apple

File contents after using preg_replace() function

Tip solutie

Permanent

Voteaza

(1 din 9 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?