gpt4 book ai didi

php - 正则表达式和 PHPUnit 断言 : count how many times word matches in repeating pattern

转载 作者:太空宇宙 更新时间:2023-11-04 15:07:46 25 4
gpt4 key购买 nike

我正在使用 PHPUnit 测试使用提供的数据生成 HTML option 标记的 PHP 函数的输出。

例如,这是函数的正确输出(我添加了换行以提高 SO 的可读性):

<option value="0">Choose one ...</option>
<option value="fooID">fooValue</option>
<option value="barID"selected>barValue</option>
<option value="bazID">bazValue</option>

为了测试输出,我使用了这个断言:

$this->assertRegExp("/(<option value=\".*\" *(selected)? *>.*<\/option>)+/i", $res);

其中 $res 是被测函数的输出字符串。

而且效果很好。但我还想检查 selected 是否仅在一个 option 标记中生成。

我该怎么做?有没有办法计算 selected 被匹配的次数?

提前致谢,请客气,这是我关于 SO 的第一个问题 :-)

最佳答案

不要使用正则表达式来解析 HTML 或 XML 文档。使用 DOM 解析器:

// create a document object from the HTML string
$doc = new DOMDocument();
$doc->loadHTML($html);

// create a XPath selector
$selector = new DOMXPath($doc);

// select nodes containing the selected attribute
$result = $selector->query('//*[@selected]');

// make assertion
$this->assertEquals(1, $result->length, 'Failed to assert that result contains exactly one selected element');

关于php - 正则表达式和 PHPUnit 断言 : count how many times word matches in repeating pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23954815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com