选择元素之间的文本内容

时间:2013-09-01 03:36:41

标签: php character explode

如何选择文字中元素之间的内容?例如,在本文中,我想选择 [] 之间的内容:

  

各位大家好[我只想选择此部分,仅此而已]。你好。你好吗? zzzzzzzzz zzzzzzzzzzzz

如果我在文字中有此文字,我可以使用:

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

我可以使用explode,但问题是爆炸不适用于两个或多个角色。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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/>";
    }
}

?>

答案 2 :(得分: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);
}
?>