'how to remove a string having special characters from a file using php
I have this file.txt file
domain.com
domain2.com
domain3.com
@*.domain6.com
domain4.com
domain5.com
and I need to remove
@*.domain6.com
using php , I am using this code
$file="file.txt";
file_put_contents($file, preg_replace("/^\@\*\.domain6\.com$/","",file_get_contents($file)));
but it does not work , anyone can explain me why it does not work and how to remove this row ?
Solution 1:[1]
You need to use
$file="file.txt";
$rx = '/^\h*@\*\.domain6\.com\h*$/mu';
file_put_contents($file, preg_replace($rx,"",file_get_contents($file)));
Details:
mu-mmakes^match start of any line and$end of any line^- start of a line\h*- any zero or more horizontal whitespaces@\*\.domain6\.com-@*.domain6.comstring\h*- any zero or more horizontal whitespaces$- end of string.
See this regex demo.
NOTE: If you have trouble with escaping special chars, in PHP, you can use
$rx = '/^\h*\Q@*.domain6.com\E\h*$/mu';
See this regex demo. All chars between \Q and \E are treated as literal chars.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
