查找不在特定标签之间的所有内容

时间:2010-03-18 09:59:06

标签: php regex preg-match-all

我正在使用

preg_match_all('/<?(.*)?>/', $bigString, $matches, PREG_OFFSET_CAPTURE);

查找<??>

之间的所有内容

现在,我想查找不在<??>之间的所有内容

我正在尝试

preg_match_all('/^(<?(.*)?>)/', $bigString, $nonmatches, PREG_OFFSET_CAPTURE);

但这似乎不起作用......

2 个答案:

答案 0 :(得分:0)

非正则表达式方法

$str=<<<EOF
1 some words
1 some more words
<?
blah blah
blah blah
?>
2 some words
2 some words <?
jdf
sdf ?>
asdf
sdfs
EOF;

$s = explode('?>',$str);
foreach($s as $v){
  $m = strpos($v,'<?');
  if($m!==FALSE){
     print substr($v,0,$m)."\n";
  }
}
print end($s);

输出

$ php test.php
1 some words
1 some more words


2 some words
2 some words

asdf
sdfs

答案 1 :(得分:0)

嗯,这个问题有多种方法。一种方法是捕获要排除的项目,找到它们的偏移量和长度,基本上只是从原始字符串中提取这些部分,而剩下的就是标记之外的部分。

这是一个函数作为例子:

<?php

function match_all_except ($pattern, $string)
{
    preg_match_all($pattern, $string, $match, PREG_OFFSET_CAPTURE);

    $parts = array();
    $pos = 0;

    foreach ($match[0] as $info)
    {
        $parts[] = substr($string, $pos, $info[1] - $pos);
        $pos = $info[1] + strlen($info[0]);
    }

    $parts[] = substr($string, $pos);

    return $parts;
}

$string = 'one<? foo ?>two<? bar ?>three';
$parts = match_all_except('/<\?.*?\?>/s', $string);

// Will output "one, two, three, "
foreach ($parts as $outside)
{
    echo "$outside, ";
}

?>

或者,您可以在/\G(?=.)((?:(?!<\?).)*)(?:<\?((?!\?>).)*(\?>|$)|$)/s中使用此正则表达式preg_match_all将标记外的所有部分捕获到子模式中。虽然,如果标签在文档中不均匀匹配,它可能有它自己的困难。

例如,

<?php

$string = 'one<? foo ?>two<? bar ?>three';
preg_match_all('/\G(?=.)((?:(?!<\?).)*)(?:<\?((?!\?>).)*(\?>|$)|$)/s', $string, $match);

// Will output "one, two, three, "
foreach ($match[1] as $outside)
{
    echo "$outside, ";
}

?>
相关问题