Nirdesh Kumawat
Nirdesh Kumawat

Reputation: 406

php preg_replace replace space in text file

i am trying to remove some content from text file using preg_replace.Content in text like below

1
    *useless*Text
                                    Steve Waugh

How to convert content like

1    Steve Waugh

my code is below.It doesn't work.I don't know where am i making mistake?

$content = file_get_contents('test.txt');
$content = preg_replace('/\s[*]useless[*]Text\s/', '  ', $content);
file_put_contents('test.txt', $content);

Upvotes: 0

Views: 161

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

If you want to keep the indenting before *useless*Text so that it is before Steve Waugh in the result, you could use a capturing group.

\h*\R(\h+)[*]useless[*]Text\s*
  • \h*\R Match 0+ horizontal whitespace chars and a Unicode newline sequence
  • (\h+) Capture group 1, match 1+ horizontal whitespace chars
  • [*]useless[*] Match *useless*
  • Text\s* Match Text and 0+ whitspace chars

See a regex demo | Php demo

In the replacement use $1

preg_replace('/\h*\R(\h+)[*]useless[*]Text\s*/', '$1', $content);

To replace with the predetermined spaces, you could use

\s*[*]useless[*]Text\s*

Regex demo

preg_replace('/\s*[*]useless[*]Text\s*/', '  ', $content);

Upvotes: 2

Related Questions