正则表达式和PHPUnit断言:计算重复模式中单词匹配的次数

Jor*_*ker 2 html php phpunit

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

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

<option value="0">Choose one ...</option>
<option value="fooID">fooValue</option>
<option value="barID"selected>barValue</option>
<option value="bazID">bazValue</option>
Run Code Online (Sandbox Code Playgroud)

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

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

where $res测试函数的输出字符串.

它运作良好.但我还要检查selected是否只在一个option标签中生成.

我怎样才能做到这一点?有没有办法计算selected匹配的次数?

提前谢谢,善待,这是我关于SO的第一个问题:-)

hek*_*mgl 5

不要使用正则表达式来解析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');
Run Code Online (Sandbox Code Playgroud)