Top Results
Top Results

Reputation: 69

preg_replace regex stop at end of line

Stuck on selecting and removing text using preg_replace. I have a starting point Address: with no end point, except that it does end with a new line. Is there a regex that will remove lines of text, using newline as your end point?

Address: 123 Main Street
City: New York

preg_replace('#Address:.*#si'), '', $lead_container)

Above removes everything including City: New York which I am looking to keep. I could use City: as my end point, except that is not always available. Prefer newline \n as the endpoint.

preg_replace('#Address:.*\n#si'), '', $lead_container)

Tried adding \n and \r to my regex. That still selects everything. If it is possible, I sure would appreciate being pointed in the right direction. Thanks

Upvotes: 1

Views: 850

Answers (2)

user4038080
user4038080

Reputation:

This starts to select after the first blank

preg_replace('[ ].*?\n', '', $lead_container)

Upvotes: 0

Nick
Nick

Reputation: 147156

You have a couple of options. Firstly, you can remove the s option on your regex; that will prevent . matching newline:

echo preg_replace('#Address:.*#i', '', $lead_container);

Secondly, you can make the regex in your second example non-greedy by adding ? after the .*:

echo preg_replace('#Address:.*?\n#si', '', $lead_container);

In both cases for sample input of

$lead_container = "Address: 123 Main Street
City: New York";

The output is City: New York. Demo on 3v4l.org

Upvotes: 2

Related Questions