Reputation: 12538
I need to detect the number of times numbers are found within a string. If the string is "1 ssdsdsd 2"
I need an array with [1,2]
in it. If the string is "1 a"
I need an array such as: [1]
.
With my below attempts, I am close, but I end up with duplicate numbers in there. Preg match seems more appropriate for what I need but duplicates matches as well.
Any idea why this is? I appreciate any suggestions on how to accomplish this.
input
preg_match_all("/([0-9]+)/", trim($s), $matches); //$s = "1 2", output below
//preg_match("/([0-9]+)/", trim($s), $matches); //$s = "1 .", outputs [1,1]
output
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 1
[1] => 2
)
)
Upvotes: 0
Views: 130
Reputation: 47991
preg_split()
is the ideal tool for this job because it will return a flat, indexed array of numbers.
Use \D+
to explode on one or more occurrences of non-numeric characters. Use the function flag to ensure there are no empty elements in the output array -- this eliminates the need to trim in advance.
Code: (Demo)
var_export(
preg_split(
'/\D+/',
$s,
0,
PREG_SPLIT_NO_EMPTY
)
);
Upvotes: 0
Reputation: 20747
You can opt to remove all non-digit chars and get the strlen()
echo strlen(preg_replace('/[^0-9]/', '', '1 ssdsdsd 2')); // 2 digits
echo strlen(preg_replace('/[^0-9]/', '', '1 ssd324sd567s.d6756 2')); // 12 digits
echo strlen(preg_replace('/[^0-9]/', '', '123456789')); // 9 digits
If you know that PHP string chars can be accessed by their index position then you can use something like:
echo preg_replace('/[^0-9]/', '', '9 ssdsdsd 5')[0]; // outputs 9 because the resulting string is '95' and position zero's value is 9
Upvotes: 0
Reputation: 91488
Remove the capture group,
preg_match_all("/[0-9]+/", trim($s), $matches);
The first element in matches array is the full match of the regex, the second one is the capture group.
Upvotes: 2