【发布时间】:2012-02-16 00:23:09
【问题描述】:
如何在此 HTML 代码中通过 PHP preg_match() 正则表达式模式匹配 subject:
<table border=0>
<tr>
<td>
<h2>subject</h2>
</td>
所有空格和换行符都是故意留下的。所以问题在于使用一些多行模式提取主题名称。
【问题讨论】:
标签: regex preg-match
如何在此 HTML 代码中通过 PHP preg_match() 正则表达式模式匹配 subject:
<table border=0>
<tr>
<td>
<h2>subject</h2>
</td>
所有空格和换行符都是故意留下的。所以问题在于使用一些多行模式提取主题名称。
【问题讨论】:
标签: regex preg-match
如果您正在寻找(例如)嵌套在h2 标记中的h2 标记 一个td 标记,其中两者之间只有空格,只需使用包含空格、换行符的\s等。例如::
preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#i',$str,$matches);
// result is in $matches[1]
看到它在行动here。
为了您的兴趣,here 是您可以传递给preg_* 函数的不同修饰符的列表。您可能感兴趣的标志是:
s ("dotall") :这个使. 匹配每个字符,包括换行符。因此,假设您的 <h2>.....</h2> 分布在多行中。那你就必须这样做
preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#is',$str,$matches);
为了让.* 遍历多行(请参阅正则表达式末尾的额外s?)。
m ("multiline") :这个只是让^ 和$ 匹配line 的开始/结束,而不仅仅是string 的开始/结束。只有当您在模式中使用 ^ 和 $ 并希望它们匹配输入中每一行的开始/结束时,您才真正需要它。【讨论】:
'/^start/im'
您可以将m 运算符添加到您的正则表达式中:
// Given your HTML content.
$html = 'Your HTML content';
preg_match('/<td[^>]*>(.*?)<\/td>/im', $html, $matches);
希望这(仍然)有帮助,哈哈哈。
【讨论】:
s 修饰符(用于“DOTALL”或“单行”模式)是您所想的,而这已经是suggested。
很简单
preg_match('/<h2>(.*?)<\\/h2>/', $str, $matches);
print($matches[1]);
多行格式对正则表达式没有影响,除非您需要匹配跨多行的字符串。
【讨论】:
您不应该使用正则表达式来解析 HTML 内容。如果您无法控制用户可以输入的内容,则可能会导致很多问题。每种语言都有很多更好的解决方案。在大多数情况下,XML 解析器做得更好。查看DOMDocument、simplehtmldom 或php-html-parser
请参阅此处了解为什么不应该在 HTML 内容上使用正则表达式的更多答案: RegEx match open tags except XHTML self-contained tags
【讨论】:
preg_match 与多行一起使用。如果您不喜欢该用例,则不回答问题。
捕获由 4 个四个反引号分隔的代码块(作为降价语法)。
易于适应的示例。
<?php
$str = '
# Some Text
````
h5 {
font-size: 1rem;
font-weight: 600;
}
````
And some text.
';
$reg = '/````[^>]*(.*?)````/';
preg_match($reg, $str, $matches);
echo $matches[0];
/* OUTPUT
````
h5 {
font-size: 1rem;
font-weight: 600;
}
````
*/
echo preg_replace($reg, "DELETED", $str);
/* OUTPUT
# Some Text
DELETED
And some text.
*/
【讨论】:
您必须在正则表达式中使用\s 删除所有换行符:
$str ="<ol>
<li>Capable for unlimited product</li>
<li>Two currency support</li>
<li>Works with touch screens and click screen based systems</li>
<li>Responsive design <b>shopping cart</b>, Specially design for Mac, iPhone, iPad, PC and Android</li>
<li>VAT for countries that support a Value Added Tax</li>
<li>Barcode scanner checkout option for POS</li>
<li>mRSS</li>
</ol>";
preg_match("/^([A-Za-z0-9\s\<\>\.\,\/\-\ ]+)$/", $str);
// Sanitize your code before save to database.
function test_input($data) {
$data = trim($data);
$data = htmlspecialchars($data);
$data = json_encode($data);
$data = addslashes($data);
return $data;
}
echo test_input($str);
【讨论】: