通过 PHP 的 preg_match() 匹配多行模式 [英] Matching a multiple lines pattern via PHP's preg_match()

查看:242
本文介绍了通过 PHP 的 preg_match() 匹配多行模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在此 HTML 代码中通过 PHP preg_match() 正则表达式模式匹配 subject:

How can I match subject via a PHP preg_match() regular expression pattern in this HTML code:

      <table border=0>
  <tr>
  <td>


  <h2>subject</h2>



    </td>

故意留下所有空格和换行符.所以问题在于使用一些多行模式提取主题名称.

All the whitespaces and newlines are left on purpose. So the problem is in extracting subject name using some multiple line pattern.

推荐答案

如果您正在寻找(例如)h2 标签嵌套 in 一个 td 标记,其中两者之间只有空格,只需使用 \s ,其中包括空格、换行符等.例如::

If you're looking for (e.g.) a h2 tag nested within a td tag where there's only whitespace in between the two, just use \s which includes spaces, newlines, etc. eg::

preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#i',$str,$matches);
// result is in $matches[1]

此处查看实际效果.

为了您的兴趣,这里是一个列表您可以传递给 preg_* 函数的不同修饰符.您可能感兴趣的标志是:

For your interest, here is a list of different modifiers you can pass in to preg_* functions. Flags that may interest you are:

  • s ("dotall") :这个使 . 匹配每个字符,包括 换行符.因此,假设您的 <h2>.....</h2> 分布在多行上.那你就得做

  • s ("dotall") : this one makes . match every character, including newlines. So, say your <h2>.....</h2> was spread over multiple lines. Then you'd have to do

preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#is',$str,$matches);

为了让 .* 跨越多行(请参阅正则表达式末尾的额外 s?).

in order to have the .* go over multiple lines (see the extra s at the end of the regex?).

这篇关于通过 PHP 的 preg_match() 匹配多行模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆