0

入力文字列の例: "[A][B][C]test1[/B][/C][/A] [A][B]test2[/B][/A] test3"

テキストのどの部分が A、B、C タグの間にないかを調べる必要があります。たとえば、上記の文字列では、'test2' と 'test3' です。「test2」には C タグがなく、「test3」にはタグがまったくありません。

次のようにネストすることもできます: 入力例 string2: "[A][B][C]test1[/B][/C][/A] [A][B]test2[C]test4[/C] [/B][/A] テスト 3"

この例では「test4」が追加されていますが、「test4」には A、B、および C タグが含まれているため、出力は変化しません。

これを解析する方法を知っている人はいますか?

4

3 に答える 3

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)
于 2012-09-24T10:06:20.573 に答える
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
于 2012-09-24T10:06:35.387 に答える
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);
于 2012-09-25T19:44:41.757 に答える