简体   繁体   中英

How do I get text containing a certain string between tags

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

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 possible
    • thistext - literal text
    • [^&]* - any 0+ chars other than & , as many as possible
  • & - a & char

PHP demo :

$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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM