2013-09-01 22 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); 
} 
?>