1

I am using str_replace to remove certain string that starts with the '#' character from a read txt file, however the html output when tested removes only the # symbol. The problem I am having is that I want to remove all of the text beginning with that particular character (including '#' too).

So far I have tried:

1)

$data = str_replace('#','',file_get_contents($strFileName));
return $data;

2)

fopen($strFileName,'r');
$remove = "#";
$tmpData = file_get_contents($strFileName);
$data = preg_replace("/.*\b" . $remove ."\b.*\n/ui", "#"  , $tmpData);
return $data;

The original text file is like this:

#

# bla bla bla 

#

# bla bla bla 

#

# bla bla bla

The first try did remove the # character but left the rest of the words. The second didn't work at all. Thanks.

ASO
  • 85
  • 6

2 Answers2

1

You can do that with preg_replace,

$data = preg_replace("/^#.*/m", "", $tmpData);
Federkun
  • 36,084
  • 8
  • 78
  • 90
  • Perfect, many thanks. Any hint on how to remove the line when the comment is indented? For instance the "#comment bla bla" is indented and the above expression does not detect it. Thanks – ASO Dec 11 '16 at 12:37
  • Add `\s`: `$data = preg_replace("/^\s*?#.*/m", "", $tmpData);` – Federkun Dec 11 '16 at 12:39
1

You indeed need to use preg_replace for replacing the #. But you need to "tell" the regex that you are processing a multi-line text, so it wont stop the replacement after the first line. You do that by applying the m modifier in the end of the regular expression pattern, so the pattern sent to preg_replace will be:

/^#.*/m - note the m in the end of the expression, which means: multiline search

This will match the following: a single # char at line start (as ^ is the line start identifier) and all the line afterwards. With the below replacment:

$data = preg_replace('/^#.*/m','',$tmpData);

Will replace the whole lines which were matched above with nothing.

Here is a working example.

Alon Adler
  • 3,984
  • 4
  • 32
  • 44