Reputation: 99
I need to output the single 3 in the array below using preg_match or preg_split, how can I accomplish this? This possibilities are 1 through 8.
VMName Count CompatibilityForMigrationEnabled CompatibilityForOlderOperatingSystemsEnabled ------ ----- -------------------------------- -------------------------------------------- ap-1-38 3 False False
I have tried the following with no success using both preg_match and preg_split:
('\\s+\\d\\s+', $output)
('\\s+[\\d]\\s+', $output)
("^[\s0-9\s]+$", $output)
("/(.*), (.*)/", $output)
Upvotes: 0
Views: 1454
Reputation: 627082
To match a 1
to 8
number that is in between whitespaces, you may use
preg_match('~(?<!\S)[1-8](?!\S)~', $s, $match)
See the regex demo.
Details
(?<!\S)
- a whitespace or start of string required immediately to the left of the current location[1-8]
- a digit from 1
to 8
(?!\S)
- a whitespace or end of string required immediately to the right of the current locationSee PHP demo:
$str = 'VMName Count CompatibilityForMigrationEnabled CompatibilityForOlderOperatingSystemsEnabled ------ ----- -------------------------------- -------------------------------------------- ap-1-38 3 False False';
if (preg_match('/(?<!\S)[1-8](?!\S)/', $str, $match)) {
echo $match[0];
}
// => 3
Note you may also use a capturing approach:
if (preg_match('/(?:^|\s)([1-8])(?:$|\s)/', $str, $match)) {
echo $match[1];
}
See the regex demo and the PHP demo.
Here, (?:^|\s)
is a non-capturing alternation group matching start of string *(^
) or (|
) a whitespace (\s
), then a digit from 1
to 8
is captured (with ([1-8])
) and then (?:$|\s)
matches the end of string ($
) or a whitespace. $match[1]
holds the necessary output.
Upvotes: 0
Reputation: 2165
Try this:
preg_match("/( \d{1} )/", $input_line, $output_array);
Examples: http://www.phpliveregex.com/p/luf
Upvotes: 1
Reputation: 1286
Give the following preg_match a try
<?php
$matched = preg_match('/( [0-9] )/', $string, $matches);
if($matched){
print_r($matches);
}
Hope this helps!
Upvotes: 2