GGGGG
GGGGG

Reputation: 159

finding the text before the keyword using regular expression in php

My String

$string = "Name : Test 123 \n req string : abc xyz 123 bla bla \n tel:234545";

my keyword is

$keyword = 'tel';

Now, I need to find the text before my keyword. I can able to find the words after the keyword using

$pattern  = '/\btel\W*(.*)$/mi'; 

But, I need a pattern from which I can find the text before the keyword. Means, I need to get abc xyz 123 bla bla if my keyword is tel. I think you got what I said.

Note : I need only the required string. But not Name. Thats the reason, I am not using explode.

plz help me in solving this. Thanks in advance!

Upvotes: 0

Views: 81

Answers (2)

sshashank124
sshashank124

Reputation: 32189

You can use the following regex by looking ahead:

/(.*)(?=(tel))/

I don't know about the php specific rules of regex but I hope you get the idea. Also, you should use the DOTALL parameter to include matching newlines

Demo:

http://regex101.com/r/mZ0wT5

Upvotes: 0

Jerry
Jerry

Reputation: 71538

Try this regex then:

([^:\r\n]+)[\r\n]+tel

regex101 demo

[^:\r\n]+ matches non colon/newlines/carriage returns.

[\r\n]+ matches newlines/carriage returns.

Upvotes: 2

Related Questions