2010-07-09 27 views
1

我想弄清楚识别括号内的内容并能够返回该内容的函数。像这样:从PHP中的字符串检索部分内容

$str = "somedynamiccontent[1, 2, 3]" 
echo function($str); // Will output "1, 2, 3" 

有人可以帮忙吗?谢谢你的时间。

回答

3
preg_match("/\[(.+)\]/",$string,$matches); 
echo $matches[1]; 
+0

谢谢,简单而短暂:) – 2010-07-09 20:39:18

1

用正则表达式简单的例子(这将匹配所有出现):

<?php 
$subject = 'hello [1,2,3], testing 123 [hello], test [_"_£!"_£]'; 
preg_match_all('/\[([^\]]+)\]/', $subject, $matches); 


foreach ($matches[1] as $match) { 

    echo $match . '<br />'; 
} 

或只是一个:

<?php 
$subject = 'hello [1,2,3], testing 123 [hello], test [_"_£!"_£]'; 
preg_match('/\[([^\]]+)\]/', $subject, $match); 


echo $match[1] . '<br />'; 

编辑:

组合成一个简单的函数。 ..

<?php 
$subject = 'hello [1,2,3], testing 123 [hello], test [_"_£!"_£]'; 

function findBrackets($subject, $find_all = true) 
{ 
    if ($find_all) { 
     preg_match_all('/\[([^\]]+)\]/', $subject, $matches); 

     return array($matches[1]); 
    } else { 

     preg_match('/\[([^\]]+)\]/', $subject, $match); 

     return array($match[1]); 
    } 
} 

// Usage: 
echo '<pre>'; 

$results = findBrackets('this is some text [1, 2, 3, 4, 5] [3,4,5] [test]', false); // Will return an array with 1 result 

print_r($results); 

$results = findBrackets('this is some text [1, 2, 3, 4, 5] [3,4,5] [test]'); // Will return an array with all results 

print_r($results); 

echo '</pre>'; 
+0

哇谢谢!一个很好的冗长的答案 – 2010-07-09 20:38:28