2013-09-01 24 views
2

如何選擇文本元素之間的內容?舉例來說,在本文中我想選擇[]之間的內容:選擇元素之間的文本內容

大家好[我要選擇僅此一節,僅此而已。你好。你好嗎?泣鬼神zzzzzzzzzzzz

如果我有裏面的文字這段文字,我可以使用:

<?php 
$a=file("text.txt"); 
print "".$a[].""; 
?> 

而且我可以用explode,但問題是,爆炸沒有按’噸工作兩個或鐵道部字符。

回答

0

這兒有你

爲例
<?php 

$s = 'Helo [everybody] [Only i need this select no more], hi [how] are you zzzzzz'; 

if (preg_match_all("^\[(.*?)\]^", $s, $matches, PREG_OFFSET_CAPTURE)) { 
    foreach ($matches[1] as $match) { 
     echo $match[0]."<br/>"; 
    } 
} 

?> 
+0

啊是完美的,因爲我的文本更多[],thank's – user2734398

3

要獲得[]之間的內容使用正則表達式: '[(*)]'

示例代碼:

$var = "Helo everybody [ Only i need this select no more ] , hi how are you zzzzzzzzz zzzzzzzzzzzz"; 

$matches = array(); 
$t = preg_match_all('/\[(.*)\]/s', $var, $matches); 
print_r($matches[1]); 

Eval

+0

如果ih更多的文字與更多[]裏面? – user2734398

+0

在這種情況下,只需將preg_match更改爲preg_match_all – Sumoanand

0
<?php 
$str = "Hello everybody [ I want to select only this section, nothing more ]. Hi. How are you? zzzzzzzzz zzzzzzzzzzzz"; 
$from = "["; 
$to = "]"; 

echo getBetween($str,$from,$to); 

function getBetween($str,$from,$to) 
{ 
    return substr(substr($str,strpos($str,$from),strlen($str)),1,strpos(substr($str,strpos($str,$from),strlen($str)),$to)-1); 
} 
?>