如何从php [duplicate]中的这个字符串中提取值

问题描述:

This question already has an answer here:

I have this string

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

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

181,183,4563

</div>

此问题已经存在 这里有一个答案: p>

  • 从字符串中提取数字 20 answers span> li> ul> div>

    我有这个字符串 p>

      @ [181] @ [183  ] @ [4563] 
      code>  pre> 
     
     

    从这个字符串我想在这种情况下得到[]之间的值 p>

    181,183,4563 p> div>

This should do the trick:

$string = '@[181] @[183] @[4563]';
preg_match_all('/\[([0-9]*)\]/', $string, $matches);
foreach($matches[1] as $number) {
    echo $number;
}

<?php 
$string = '@[181] @[183] @[4563]';
preg_match_all("#\[([^\]]+)\]#", $string, $matches); //or #\[(.*?)\]#
print_r($matches[1]);
?> 

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

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

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]);