Extract 2 numbers out of string between [ ] brackets

Posted on 2008-11-19
Last Modified: 2013-12-13
I have a string that may contain 2 numbers in brackets
$string = "this is a string[40] and there may or may not be another [10] in brackets";

i need to get

$a = 40;
$b= 10;

There may often only be one number , sometimes 2.
Question by:samkay
    LVL 39

    Accepted Solution

    Try this:
    $string = "this is a string[40] and there may or may not be another [10] in brackets";
    if(count($matches[1])>0) $a = $matches[1][0];
    if(count($matches[1])>1) $b = $matches[1][1];
    echo 'a='.$a.' b='.$b;

    Open in new window


    Author Closing Comment


    Featured Post

    What Is Threat Intelligence?

    Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

    Join & Write a Comment

    This is a general how to create your own custom plugin system for your PHP application that you designed (or wish to extend a third party program to have plugin functionality that doesn't have it yet).  This is not how to make plugins for existing s…
    Both Easy and Powerful How easy is PHP? (  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
    Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    732 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now