PHP:如何在特定标签之间找不到文本?

时间:2012-09-24 09:52:16

标签: php parsing text tags

示例输入字符串:“[A] [B] [C] test1 [/ B] [/ C] [/ A] [A] [B] test2 [/ B] [/ A] test3”

我需要找出A,B和C标签之间的文本部分。因此,例如,在上面的字符串中,它是'test2'和'test3'。 'test2'没有C标签,'test3'根本没有任何标签。

如果也可以这样嵌套: 示例输入字符串2:“[A] [B] [C] test1 [/ B] [/ C] [/ A] [A] [B] test2 [C] test4 [/ C] [/ B] [/ A] TEST3"

在此示例中添加了“test4”,但“test4”具有A,B和C标记,因此输出不会更改。

任何人都知道如何解析这个问题?

3 个答案:

答案 0 :(得分:1)

这个解决方案并不干净,但它可以解决问题

$string = "[A][B][C]test1[/B][/C][/A] [A][B]test2[/B][/A] test3" ;
$string = preg_replace('/<A[^>]*>([\s\S]*?)<\/A[^>]*>/', '', strtr($string, array("["=>"<","]"=>">")));
$string = trim($string);
var_dump($string);

输出

 string 'test3' (length=5)

答案 1 :(得分:0)

考虑到你们每个人的标签都在[A]中[/ A]你可以做的是:爆炸[/ A]并验证每个数组是否包含[A]标签,如下所示:

$string = "[A][B][C]test1[/B][/C][/A] [A][B]test2[/B][/A] test3";

$found = ''; // this will be equal to test3
$boom = explode('[/A]', $string);

foreach ($boom as $val) {
 if (strpos($val, '[A] ') !== false) { $found = $val; break; }
}

echo $found; // test3

答案 2 :(得分:0)

尝试以下代码

$str = 'test0[A]test1[B][C]test2[/B][/C][/A] [A][B]test3[/B][/A] test4';
$matches  = array();

// Find and remove the unneeded strings
$pattern = '/(\[A\]|\[B\]|\[C\])[^\[]*(\[A\]|\[B\]|\[C\])[^\[]*(\[A\]|\[B\]|\[C\])([^\[]*)(\[\/A\]|\[\/B\]|\[\/C\])[^\[]*(\[\/A\]|\[\/B\]|\[\/C\])[^\[]*(\[\/A\]|\[\/B\]|\[\/C\])/';
preg_match_all( $pattern, $str, $matches );
$stripped_str = $str;
foreach ($matches[0] as $key=>$matched_pattern) {
  $matched_pattern_str  = str_replace($matches[4][$key], '', $matched_pattern); // matched pattern with text between A,B,C tags removed
  $stripped_str = str_replace($matched_pattern, $matched_pattern_str, $stripped_str); // replace pattern string in text with stripped pattern string
}

// Get required strings
$pattern = '/(\[A\]|\[B\]|\[C\]|\[\/A\]|\[\/B\]|\[\/C\])([^\[]+)(\[A\]|\[B\]|\[C\]|\[\/A\]|\[\/B\]|\[\/C\])/';
preg_match_all( $pattern, $stripped_str, $matches );
$required_strings = array();
foreach ($matches[2] as $match) {
  if (trim($match) != '') {
    $required_strings[] = $match;
  }
}

// Special case, possible string on start and end
$pattern = '/^([^\[]*)(\[A\]|\[B\]|\[C\]).*(\[\/A\]|\[\/B\]|\[\/C\])([^\[]*)$/';
preg_match( $pattern, $stripped_str, $matches );
if (trim($matches[1]) != '') {
  $required_strings[] = $matches[1];
}
if (trim($matches[4]) != '') {
  $required_strings[] = $matches[4];
}

print_r($required_strings);