简体   繁体   English

在HTML类标签之间匹配文本

[英]Match text between HTML class tags

I got the following HTML code: 我得到以下HTML代码:

<ul class='ips'>my_content</ul>

Now, how can I preg_match_all this, to match only the my_content text? 现在,我该如何preg_match_all这只匹配my_content文本?

I was trying answers from this question: Preg match text in php between html tags but modifying the regex result in selecting the whole code including HTML tags. 我正在尝试回答以下问题: 在html标签之间预匹配php中的文本,但修改正则表达式会导致选择包括HTML标签在内的整个代码。

The following regex will work for matching between the tags. 以下正则表达式可用于标签之间的匹配。

It will match: 它将匹配:

<ul class='ips'>... 

With single quotes and double quotes. 用单引号和双引号。

$string = "<ul class='ips'>my_content</ul>";
preg_match_all('/[^>]class=["\']ips[\'"]*>(.*?)<\//',
           $string,
           $matches,
           PREG_PATTERN_ORDER);
print_r($matches);

If you don't care if it is a div, ul or etc, remove the <ul and ul> from the regex pattern. 如果您不在乎它是div,ul还是其他,请从正则表达式模式中删除<ulul>

Response from above: 上方回应:

Array
(
[0] => Array
    (
        [0] => <ul class="ips">my_content</ul>
    )

[1] => Array
    (
        [0] => my_content
    )

)

Here, use this RegEx to allow variations: 在这里,使用此RegEx允许变化:

/[^>]class\s*=\s*["\'].*ips.*[\'"].*>/
  • spaces before or after equals sign 等号前后的空格
  • multiple class names in one class attribute 一个类属性中有多个类名
  • multiple attributes after the class attribute 类属性后有多个属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM