简体   繁体   English

如何使用preg match获取此html标签的内容?

[英]How to use preg match to get the contents of this html tag?

I am trying to get at the desired content in this tag: 我试图在此标签中获得所需的内容:

<p class="address">
desired content
</p>

this is my attempt: 这是我的尝试:

preg_match_all("/\<p class=\"address\">(.*)\<\/p\>/", $contents, $matches);

But the $matches array is empty. 但是$ matches数组为空。 Please help. 请帮忙。

Thanks 谢谢

You could try this: 您可以尝试以下方法:

$contents = '<p class="address">desired content</p>';
$res = preg_match_all("/\<p class=\"address\">(.*)\<\/p\>/s", $contents, $matches);
var_dump($res);
var_dump($matches);

$matches is not empty, right? $ matches不为空,对吗?

  1. you need to set the PCRE_DOTALL flag to make . 您需要将PCRE_DOTALL标志设置为make . also match \\n - see modifiers 也匹配\\n查看修饰符
  2. use .*? 使用.*? (ungreedy operator) to not prevent matching </p> in the capture group (不稳定的运算符)以防止在捕获组中匹配</p>
  3. you can use a different pattern delimiter and single quotes to remove all the backslashes, makes your pattern much more readable! 您可以使用其他模式定界符和单引号删除所有反斜杠,从而使您的模式更具可读性!

like so: 像这样:

<?php
$contents = '<p class="address">
desired content
</p>';
$res = preg_match_all('#<p class="address">(.*?)</p>#s', $contents, $matches);
var_dump($matches);

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

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