duanluan2047 2014-05-30 12:36
浏览 89
已采纳

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

I'm using PHPUnit to test the output of a PHP function that produces HTML option tags using provided data.

For example, this is a correct output of the function (I added line returns to improve readability on SO):

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

And to test the output, I'm using this assertion:

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

where $res is the output string of the tested function.

And it works well. But I would like to also check that selected is generated in only one option tag.

How can I do this? Is there a way to count how many times selected was matched?

Thanks in advance, be kind, it's my first question on SO :-)

  • 写回答

1条回答 默认 最新

  • dongtanliefang8765 2014-05-30 12:43
    关注

    Don't use regexes to parse HTML or XML documents. Use a DOM parser:

    // 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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?