1

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.

2 Answers 2

3
preg_match("/\[(.+)\]/",$string,$matches);
echo $matches[1];
Sign up to request clarification or add additional context in comments.

Comments

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>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.