2012-09-24 46 views
0

輸入字符串示例:「[A] [B] [C] test1 [/ B] [/ C] [/ A] [A] [B] test2 [/ B] [/ A] test3」PHP:如何在特定標籤之間找到文本?

我需要找出哪些文本部分不在A,B和C標籤之間。因此,例如,在上面的字符串中,它是'test2'和'test3'。 'test2'沒有C標籤,'test3'根本沒有任何標籤。

如果還可以像這樣嵌套: 例子輸入string2:「[A] [B] [C] test1 [/ B] [/ C] [/ A] [A] [B] test2 [C] test4「

在本例中添加了」test4「,但」test4「有A,B和C標記,所以輸出不會改變。

任何人都有一個想法,我可以解析這個?

+0

外表成正則表達式 – CosminO

+0

@Erik將標籤總是以相同的順序'[A] [B] [C] [/ C] [/ B] [A]'? – air4x

+0

不,標籤可以是任何順序,並且結束標籤可以以與開啓標籤不同的順序 – Erik

回答

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) 
+0

不起作用..它也應該返回test2,因爲它不在[C]標籤中... – Erik

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 
+0

this won沒有工作。不支持嵌套標籤,甚至輸出錯誤,因爲「test2」不在[C]標籤內,因此應該已經找到了......我不認爲這可以通過簡單的爆炸() – Erik

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); 
相關問題