2010-07-09 60 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