简体   繁体   English

如何在php上使用preg_match_all在两种模式之间选择内容?

[英]How do I select content between two patterns with preg_match_all on php?

Im trying to search for two HTML tags, and also grab everything in between. 我正在尝试搜索两个HTML标记,并同时获取它们之间的所有内容。 When I try each of the tags separately it finds them fine, so I know that they are spelled right and exist. 当我分别尝试每个标签时,会发现它们很好,因此我知道它们拼写正确并且存在。 The problem I think is with the pattern, can someone please help me with it. 我认为模式存在问题,有人可以帮助我吗。 Everything I research online seems to go right over my head. 我在网上研究的所有内容似乎无所适从。 So if you could please explain how your pattern works, that would be awesome! 因此,如果您能解释一下您的模式如何工作,那就太好了!

See code below, and if you have any questions feel free to ask. 请参阅下面的代码,如果您有任何疑问,请随时提问。

Thanks for your time:) 谢谢你的时间:)

<?php
$date= date(Y)."/".date(n)."/".date(j);
$address= "http:www.example.com/".$date;
$text_page = file_get_contents("$address");

$searchfor1 = '<li id="menuSynchronizeSwitch">';
$searchfor2 = '<li  id="footerPrevWeek';

header('Content-Type: text/plain');

$pattern1 = preg_quote($searchfor1, '/');
$pattern2 = preg_quote($searchfor2, '/');

$pattern = "/^.*$pattern1.*\r*$pattern2.*\$/m";


if(preg_match_all($pattern, $text_page, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}
?>

尝试使用$pattern = '/\\<li id\\="menuSynchronizeSwitch"\\>.*\\<li id\\="footerPrevWeek/si';请注意/s ,它允许点匹配换行符,我怀疑是是什么导致此操作失败。

You'll need to group each pattern with parenthesis 您需要使用括号将每个模式分组

like this: 像这样:

$pattern = "/(some pattern)/"; $ pattern =“ /(某些模式)/”;

and you can get each group by going through the $matches array 您可以通过$ matches数组获取每个组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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