如何选择文本元素之间的内容?例如,在此文本中,我想选择[和]之间的内容:
大家好[我只想选择这个部分,仅此而已]。你好。你好吗?zzzzzzzz zzzzzzzzzzzz
如果我在文本中有这个文本,我可以使用:
<?php
$a=file("text.txt");
print "".$a[]."";
?>
我可以使用explode
,但问题是 explode 不适用于两个或更多字符。
要获取 [] 之间的内容,请使用以下正则表达式:'[(.*)]'
示例代码:
$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]);
这是一个给你的例子
<?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/>";
}
}
?>
<?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);
}
?>