Retrieving partial content from string in PHP
I'm trying to figure out a function that recognizes content within brackets and is able to return that content. Like so:
$str = "somedynamiccontent[1, 2, 3]"
echo function($str); // Will output "1,开发者_运维知识库 2, 3"
Anybody here who can help? Thanks for your time.
preg_match("/\[(.+)\]/",$string,$matches);
echo $matches[1];
Simple example with regex (this will match all occurances):
<?php
$subject = 'hello [1,2,3], testing 123 [hello], test [_"_£!"_£]';
preg_match_all('/\[([^\]]+)\]/', $subject, $matches);
foreach ($matches[1] as $match) {
echo $match . '<br />';
}
or just the one:
<?php
$subject = 'hello [1,2,3], testing 123 [hello], test [_"_£!"_£]';
preg_match('/\[([^\]]+)\]/', $subject, $match);
echo $match[1] . '<br />';
EDIT:
Combined into a simple function...
<?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>';
精彩评论