如何使用PHP preg_match()正则表达式模式匹配此HTML代码中的subject:
<table border=0>
<tr>
<td>
<h2>subject</h2>
</td>
所有的空格和换行符都是有意留下的。因此,问题在于使用某个多行模式提取主题名称。
如何使用PHP preg_match()正则表达式模式匹配此HTML代码中的subject:
<table border=0>
<tr>
<td>
<h2>subject</h2>
</td>
所有的空格和换行符都是有意留下的。因此,问题在于使用某个多行模式提取主题名称。
td
标签中的 h2
标签,两者之间只有空格,并且需要包含空格、换行符等,请使用 \s
。例如:preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#i',$str,$matches);
// result is in $matches[1]
在此处可以看到它的效果:这里。
为您提供这里不同修饰符列表,您可以传递给preg_*
函数。可能会有用的标志包括:
s
("dotall"):使得.
匹配每个字符,包括换行符。因此,如果您的<h2>.....</h2>
跨越多行,则需要执行下面的操作:
preg_match('#<td>\s*<h2>(.*?)</h2>\s*</td>#is',$str,$matches);
为了让.*
可以跨越多行(请看正则表达式末尾的额外s
?)。
m
("multiline"):这个选项只是允许^
和$
匹配每行的开头和结尾,而不仅仅是整个字符串的开头和结尾。如果您在模式中使用^
和$
并希望它们与输入中每个单独行的开头和结尾匹配,则只有在需要时才需要它。'/^start/im'
。 - Derek Illchuk您可以在正则表达式中添加m
运算符:
// Given your HTML content.
$html = 'Your HTML content';
preg_match('/<td[^>]*>(.*?)<\/td>/im', $html, $matches);
希望这 (仍然) 有所帮助,哈哈哈。
s
修饰符(用于“DOTALL”或“单行”模式),这已经被建议过了。建议链接:https://dev59.com/Rmox5IYBdhLWcg3wzXel#8959000。 - Alan Moore您不应该使用正则表达式来解析HTML内容。如果无法控制用户输入,这可能会导致许多问题。每种语言都有更好的解决方案。在大多数情况下,XML解析器的效果更好。请查看DOMDocument, simplehtmldom或php-html-parser。
有关为什么不应该在HTML内容上使用正则表达式的更多答案,请参见此处:RegEx match open tags except XHTML self-contained tags
preg_match
。如果您不喜欢这个用例,那么它并没有回答问题。 - Manngopreg_match('/<h2>(.*?)<\\/h2>/', $str, $matches);
print($matches[1]);
多行格式对正则表达式没有影响,除非你需要匹配跨越多行的字符串。
使用4个反引号(作为Markdown语法)来捕获一个代码块。
例子易于适应。
<?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);