下面是这个场景
我使用这个正则表达式在div标记中使用id test1或tes2或test3获取文本
<div id = "test1">text</div>
<div id = "test2">text</div>
<div id = "test3">text</div>
$id_value = "test1" or "test2" or "test3";
$regex = "#\<div id=\"".$id_value."\"\>(.+?)\<\/div\>#s";
我唯一的要求是在下面的场景中从div标记获取文本
<div id="test" class="testing" style="color:red" etc etc .... more attributes >text</div>
例如,id是div标记的第一个属性,可以后面跟着n个属性。如何仅通过regex从这样的标记中提取文本。
我甚至试过
$regex = '#<div\s+.*?id="".$id_value."".*?>(.*?)</\s*div>#ims';
当$id_value = " test1“时,它返回div标记的文本,但是如果$id_value=" test2”,则返回节点test1和test2的文本值。如果$id_value="test3“,则返回所有3个节点的文本值。我只需要与特定id相关的文本值。只使用Regex .
请帮忙谢谢你。
发布于 2012-08-02 09:35:40
不要使用RegExp来解析HTML。相反,使用PHP的DOM扩展,它可以正确地解析任何类型的HTML。
示例:
<?php
$html = <<<HTML
<div id = "test1">text</div>
<div id = "test2">other text</div>
<div id = "test3">new text</div>
HTML;
$id_list = array(
"test1",
"test2",
"test3",
);
$doc = new DOMDocument();
$doc->loadHTML($html);
foreach ($id_list as $id) {
$div = $doc->getElementById($id);
if ($div == NULL) {
echo "There's no element with an ID of $id<br>\n";
}
else {
echo "$id's content is: " . $div->textContent . "<br>\n";
}
}
如果并且只有当您绝对必须使用RegExp时,我才会想到:
<?php
$html = <<<HTML
<div id = "test1">text</div>
<div id = "test2">other text</div>
<div id = "test3">new text</div>
HTML;
$id_list = array(
"test1",
"test2",
"test3",
);
foreach ($id_list as $id) {
$pattern = <<<REGEX
/
<div\s* #Opening Tag
(?: #Attributes before ID
[a-z]+ #Attribute name
\s*=\s* #Equals
(?:"[^"]*"|'[^']*') #Attribute content
\s* #Spaces?
)* #Many or none
(?: #ID Attribute
id
\s*=\s*
(?:"$id"|'$id') #Matches the ID
\s*
)
[^>]* #Anything after ID
> #Closing Tag
([^<]*) #Actual content!
<\/div>
/xi
REGEX;
preg_match_all($pattern, $html, $matches);
var_dump($matches);
}
请注意,如果使用此代码,unh̶oly͘͘c̀h̶i͏l҉d wį会流处女的血。国际货币基金组织( <cent
er> )无法维持这一局面,为时已晚。
https://stackoverflow.com/questions/11782792
复制相似问题