[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Extract 2 numbers out of string between [ ] brackets

Posted on 2008-11-19
2
Medium Priority
?
732 Views
Last Modified: 2013-12-13
I have a string that may contain 2 numbers in brackets
eg.
$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.
0
Comment
Question by:samkay
2 Comments
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 200 total points
ID: 22995315
Try this:
<?php
 
$string = "this is a string[40] and there may or may not be another [10] in brackets";
preg_match_all('/\[([\d]+)\]/',$string,$matches);
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

0
 

Author Closing Comment

by:samkay
ID: 31518273
thanks
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
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…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses
Course of the Month19 days, 10 hours left to enroll

872 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