0

I have this string

@[181] @[183] @[4563]

from this string I want to get values between [] in this case

181,183,4563

Manish
  • 1,946
  • 2
  • 24
  • 36
  • 1
    Look into regex and `preg_match_all()`, which makes it quite simple. – mario Jul 15 '13 at 22:09
  • check out Preg_match() i believe this will help more than explode() or str_replace()....there are tons of examples of how to extract numbers... – A.O. Jul 15 '13 at 22:09

4 Answers4

3

This should do the trick:

$string = '@[181] @[183] @[4563]';
preg_match_all('/\[([0-9]*)\]/', $string, $matches);
foreach($matches[1] as $number) {
    echo $number;
}
Niklas
  • 23,674
  • 33
  • 131
  • 170
Tobias Golbs
  • 4,586
  • 3
  • 28
  • 49
2
<?php 
$string = '@[181] @[183] @[4563]';
preg_match_all("#\[([^\]]+)\]#", $string, $matches); //or #\[(.*?)\]#
print_r($matches[1]);
?> 

Array
(
    [0] => 181
    [1] => 183
    [2] => 4563
)
2

I know it might sound sexy to use regex and all, but this is a case where you might not need the full power/overhead, as you have a very well formatted input string.

$string = '@[181] @[183] @[4563]';
$needles = array('@', '[', ']');
$cleaned_string = str_replace($needles, '', $string);
$result_array = explode(' ', $cleaned_string); 
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Or you could replace space with comma instead of exploding, given he wants to output it as `181,183,4563` – Prix Jul 15 '13 at 22:22
0

assuming the values between the array are numbers this is pretty simple

 $s =  '@[181] @[183] @[4563]';
 preg_match_all('/\d+/', $s, $m);

 $matches_as_array = $m[0];
 $matches_as_string = implode(',', $m[0]);
Jay Harris
  • 4,201
  • 17
  • 21