繁体   English   中英

正则表达式,用于在带或不带id属性的标签之间获取字符串

[英]Regular expression to get string between tags with or without id attribute

我有一个像下面的字符串。 我想写一个preg_match_all()函数来获得' one '和' two ' 为了获得理想的结果,必须对下面的表达式做些什么改变?

$featureTab = "<li>one</li><li id='someId'>two</li>";

我试过下面的代码。

preg_match_all('/(?<=\<li\>)(.*?)(?=\<\/li\>)/', $featureTab ,$matches);

但它只是返回' '。 因为pregx只考虑li标签之间的字符串而不是id 帮我一个正则表达式,将返回一个两个

你可以简单地使用下面的正则表达式

<li.*?>(.*?)<\/li>

在这里

`<li.*?>` here `(.*)` is to capture all attributes of `li` and `?` is to if no attributes is defined or not even space count also

由于两者都有不同的li结构

你可以检查一下

演示

注意:对于HTML/XML解析,不要使用正则表达式,您只需使用DOMDocument即可

你可以使用这个正则表达式:

<li[^>]*>(.*?)<\/li>

$re = '/<li[^>]*>(.*?)<\/li>/';
$str = '<li>one</li><li id=\'someId\'>two</li>';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

在这里查看结果: https//3v4l.org/arFRq

暂无
暂无

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

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