开发者

Can I use preg_replace to strip the trailing \n in multiline mode?

开发者 https://www.devze.com 2023-02-18 13:55 出处:网络
I just answered a question here, which has left me asking my own question. Basically, the OP wanted any line to be removed if it contained a string. Here is a regex I came up with...

I just answered a question here, which has left me asking my own question.

Basically, the OP wanted any line to be removed if it contained a string. Here is a regex I came up with...

$str = preg_replace('/^.*\b["(]?hello["(]?\b.*$/m', '', $str);

It works great, but because $ matches before the trailing \n, they rem开发者_Go百科ain when replaced and there are blank lines, e.g.

string(90) "
What it shouldhello do is:


could be words in between brackets and inverted commas also."

I can't use \z because I'm in multiline mode (at least that is what I think).

If I use s modifier, the . become too greedy and don't work across the newlines.

I have tried a few things (such as [^\n] and [\s\S]), and now I am stumped.

How can I match that trailing \n here so it is removed with the replace?


Use \n instead of $.

$str = preg_replace('/^.*\b["(]?hello["(]?\b.*\n/m', '', $str);

This misses the last line if it had hello in it, so here's a step further.

$str = preg_replace('/^.*\b["(]?hello["(]?\b.*(\n|$)/m', '', $str);

The issue now is that the last line is removed, but there is still a \n character (similar issue you're already having).

Note: I'm not a regular expression expert at all, just can usually do enough for my needs.


I feel pretty silly for not figuring this one out, but I used Jacob's answer as a basis...

$str = preg_replace('/^.*\b["(]?hello["(]?\b.*\n?/m', '', $str);

Looks like I was just too keen to use the end of line anchor.

This one allows for the optional \n at the end. It also leaves a \n at the end of the last non matched line, but I could always then trim($str).


Please try this:

$str = preg_replace('/^.*?\b["(]?hello["(]?\b.*?$/s', '', $str);

.*? makes it non-greedy.

0

精彩评论

暂无评论...
验证码 换一张
取 消