Reputation: 113
Please help me out with preg_match, I can't figure it out :(
I have a lot of text but I need to capture everything between "&" that contains a certain text.
example
"thisip4:isatextexample&ineed.thistext&TXT:&andthis.idontneed&txt:&test.thistext&"
I need to extract the complete text between & containing thistext
the result should be : ineed.thistext
AND : test.thistext
Many many many thanks in advance :)
oh I've tried using this;
&([^\\n]*thistext[^\\n]*)&
but that will not work with multiple '&'
W
Upvotes: 1
Views: 118
Reputation: 627607
Your pattern contains [^\n]*
that matches any 0+ chars other than newlines, and that makes the regex engine match across any &
chars greedily and find the last &
on the line.
You may use
'~&([^&]*?thistext[^&]*)&~'
Then, grab Group 1 value. See the regex demo.
Details
&
- a &
char ([^&]*?thistext[^&]*)
- Capturing group 1:
[^&]*?
- any 0+ chars other than &
, as few as possiblethistext
- literal text [^&]*
- any 0+ chars other than &
, as many as possible&
- a &
char $str = 'thisip4:isatextexample&ineed.thistext&TXT:&andthis.idontneed&txt:&test.thistext&';
if (preg_match_all('~&([^&]*?thistext[^&]*)&~', $str, $m)) {
print_r($m[1]);
}
// => Array ( [0] => ineed.thistext [1] => test.thistext )
Upvotes: 1