preg_replace regex,将字符串拆分为数组


preg_replace regex, split string to array

我有一个字符串,其中我需要将一些值拆分为一个数组,什么是最好的方法?

字符串可以如下所示:

<span class="17">118</span><span style="display: inline">.</span><span style="display:none"></span>

125<span class="17">25</span>354

规则是:

  1. 字符串可以以数字开头,后跟span或div
  2. 字符串可以以span或div开头
  3. 字符串可以以数字结尾
  4. 字符串可以以/span或/div结尾
  5. div/span可以有一个样式/类

我需要的是分离字符串,这样我就可以分离元素,比如:

0 => 123
1 => <span class="potato">123</span>
2 => <span style="color: black">123</span>

我尝试过一些costum regex,但regex不是我的强项:

$pattern = "/<div.(.*?)<'/div>|<span.(.*?)<'/span>/";
// i know it wont detect a number value prior to the div, thats also an issue, even if it worked

我不能使用simple_html_dom必须使用REGEX。

在每个><可能有效,但">(.*?)<"在<出于某种原因?

如果您只需将此字符串加载到DOM,然后手动解析它来编程您的逻辑,您可能会获得更好的性能,例如:

var el = document.createElement( 'div' );
el.innerHTML = '125<span class="17">25</span>354';
// test your first element (125) index=0 (you can make for loop)
if(el.childNodes[0].nodeType == 3) alert('this is number first, validate it');
else if(el.childNodes[0].nodeType == 1) alert('this is span or div, test it');
// you can test for div or span with el.childNodes[0].nodeName
// store first element to your array
// then continue, test el.childNodes[next one, index=1 (span)...]
// then continue, test el.childNodes[next one, index=2 (354)...]

既然你已经知道你在寻找什么,这可以像一样简单

尝试/(<(span|div)[^>]*>)*([^<]*)(<'/(span|div)>)*/

Regex说,"可以有一个span或div,也可以什么都没有,然后它必须是某个东西,然后是/span或/div,或者什么都没有",整个语句可以匹配零或多次。

以下是一个示例:

$pattern = "/(<(span|div)[^>]*>)*([^<]*)(<'/(span|div)>)*/";
$txt = '<span class="17">118</span><span style="display: inline">.</span><span style="display:none"></span>';
preg_match_all($pattern, $txt,$foo);
print_r($foo[0]);
$txt = '125<span class="17">25</span>354';
preg_match_all($pattern, $txt,$foo);
print_r($foo[0]);
?>