我一直在使用\K
,但最近我意识到它不能在低于5.2.4版本的PHP中工作。所以我在寻找一种不同的方式。
<?php
$html = '<div>hello</div>
<div class="someclass">hi</div>
<div class="sample">this text should be included</div>
<div>bye</div>
';
// $pattern = '/<div.+class=["\']sample["\'].+div>\K/i'; // <-- this doesn't work below v5.2.4
$pattern = '/(?<=<div.+class=["\']sample["\'].+div>)/i'; // causes an error.
$array = preg_split($pattern, $html);
print_r($array);
?>
我已经看到可以使用(?<=)
作为替代方案,我尝试了一下,但它导致了错误。有什么建议吗?
发布于 2012-09-15 13:42:27
好吧,我找到了一个变通办法。preg_split()
接受第四个参数中的PREG_SPLIT_DELIM_CAPTURE
标志,因此匹配的字符串可以包含在数组的分隔元素中。我只需要选择一个额外的元素来提取字符串,这不是那么多的工作要做。
<?php
$html = '<div>hello</div>
<div class="someclass">hi</div>
<div class="sample">this text should be included</div>
<div>bye</div>
';
$pattern = '/(<div.+class=["\']sample["\'].+div>)\${0}/i';
$array = preg_split($pattern, $html, null, PREG_SPLIT_DELIM_CAPTURE);
print_r($array);
?>
发布于 2012-09-15 13:43:15
我会重新实现split
。在Perl中,它看起来如下所示:
my @matches;
while (/\G((?s:.*?)...)/gc) {
push @matches, $1;
}
push @matches, /\G(.+)\z/sg;
https://stackoverflow.com/questions/12434528
复制相似问题