我正在使用
preg_match_all('/<?(.*)?>/', $bigString, $matches, PREG_OFFSET_CAPTURE);
查找和之间的所有<?
内容?>
现在我想找到不在和之间的<?
一切?>
我正在尝试
preg_match_all('/^(<?(.*)?>)/', $bigString, $nonmatches, PREG_OFFSET_CAPTURE);
但这似乎不起作用...
我正在使用
preg_match_all('/<?(.*)?>/', $bigString, $matches, PREG_OFFSET_CAPTURE);
查找和之间的所有<?
内容?>
现在我想找到不在和之间的<?
一切?>
我正在尝试
preg_match_all('/^(<?(.*)?>)/', $bigString, $nonmatches, PREG_OFFSET_CAPTURE);
但这似乎不起作用...
非正则表达式方法
$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
嗯,有多种方法可以解决这个问题。一种方法是捕获您要排除的项目,找到它们的偏移量和长度,基本上只是从原始字符串中提取这些部分,剩下的就是标签之外的部分。
下面以一个函数为例:
<?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, ";
}
?>