How to delete a specific content 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 deletes a specific content from the file using preg_replace() function.

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]/’, ”, $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
mngo pple ppy guv pple grpes mngo pple

Tip solutie

Permanent

Voteaza

(3 din 9 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?