alreadycoded.com
alreadycoded.com

Reputation: 326

PHP preg_match matching text between multiple occurrance of same tags

How to match text

$line = "study of 557 adults suffering from sleep";

from

 $content = "The International Journal of Nursing published a
<b>study of 557 adults suffering</b>
<br>
<b>from sleep</b>
disorders. In this study, music was played when they ...";

and somtimes the content can be

 $content = "The International Journal of Nursing published a
<b>study of 557 adults suffering from sleep</b>
disorders. In this study, music was played when they ...";

so i need one solution that can be applicable on both

preg_match("#<b>$line</b>#is",$content,$match);

Upvotes: 1

Views: 139

Answers (3)

T. AKROUT
T. AKROUT

Reputation: 1717

You can use this regex (https://regex101.com/r/elRsha/2):

$line = "study of 557 adults suffering from sleep";

$content = "The International Journal of Nursing published a
<b>study of 557 adults suffering</b>
<br>
<b>from sleep</b>
disorders. In this study, music was played when they ...";

$line = implode('(?:[\n\s\t]*(?:<.+>)*[\n\s\t]*)*', explode(' ', $line));

preg_match("#($line)#is",$content,$match);
print_r($match);

Upvotes: 0

dhaval
dhaval

Reputation: 190

First remove HTML tag from string using strip_tags function and then remove newlines from string.

$line = "study of 557 adults suffering from sleep";

$content = "The International Journal of Nursing published a
<b>study of 557 adults suffering</b>
<br>
<b>from sleep</b>
disorders. In this study, music was played when they ...";

echo preg_match("#$line#is",trim(preg_replace('/\s+/', ' ', strip_tags($content))),$match);

Upvotes: 0

Andreas
Andreas

Reputation: 23958

Like this? https://regex101.com/r/PDehGB/2

$pattern = '/<b>study.*?of.*?557.*?adults.*?suffering.*?from.*?sleep<\/b>/ms';

With this pattern it will take care of any new lines and still keep the $line.

You can explode the $line on " " and build the pattern with implode(".*?", $arr)

Upvotes: 3

Related Questions