php
PHP regex to extract special string
I am trying to use regex to extract a certain syntax, in my case something like "10.100" or "20.111", in which 2 numbers are separated by dot(.) . So if I provide "a 10.100", it will extract 10.100 from the string. If I provide "a 10.100 20.101", it will extract 10.100 and 20.101. Until now I have tried to use preg_match('/^.*([0-9]{1,2})[^\.]([0-9]{1,4}).*$/', $message, $array); but still no luck. Please provide any suggestion because I don't have strong regex knowledge. Thanks.
You may use \b[0-9]{1,2}\.[0-9]{1,4}\b See the regex demo. Details: \b - a leading word boundary [0-9]{1,2} - 1 or 2 digits \. - a dot [0-9]{1,4} - 1 to 4 digits \b - a trailing word boundary. If you do not care about the whole word option, just remove \b. Also, to match just 1 or more digits, you may use + instead of the limiting quantifiers. So, perhaps [0-9]+\.[0-9]+ will also work for you. See a PHP demo: $re = '/[0-9]+\.[0-9]+/'; $str = 'I am trying to use regex to extract a certain syntax, in my case something like "10.100" or "20.111", in which 2 numbers are separated by dot(.) . So if I provide "a 10.100", it will extract 10.100 from the string. If I provide "a 10.100 20.101", it will extract 10.100 and 20.101.'; preg_match_all($re, $str, $matches); print_r($matches[0]); Output: Array ( [0] => 10.100 [1] => 20.111 [2] => 10.100 [3] => 10.100 [4] => 10.100 [5] => 20.101 [6] => 10.100 [7] => 20.101 )
Regex: /\d+(?:\.\d+)/ 1. \d+ for matching digits one or more. 2. (?:\.\d+) for matching digits followed by . like .1234 Try this code snippet here <?php ini_set('display_errors', 1); $string='a 10.100 20.101'; preg_match_all('/\d+(?:\.\d+)/', $string, $array); print_r($array); Output: Array ( [0] => Array ( [0] => 10.100 [1] => 20.101 ) )
$decimals = "10.5 100.50 10.250"; preg_match_all('/\b[\d]{2}\.\d+\b/', $decimals, $output); print_r($output); Output: Array ( [0] => 10.5 [1] => 10.250 ) Regex Demo | Php Demo
Related Links
Merge these array values into a new array?
Compare directory contents to database column in Joomla
How to access the html contents in the php code segment within the same php file?
How to change the index name of array
New line chr in twitter feed breaks JSONP
FFmpeg failed to transcode - Error while opening encoder for output stream
need ideas for remote authentication (Wordpress) [closed]
get parent array name after array_walk_recursive function
How To Insert From Data From PHP to MySQL DB
Form, receive variables on same php file [duplicate]
Arrays and nested foreach
Sidenavigation. Load everything with one request or splitted?
Display TinyMCE inputted text causing undisplayable characters
how to echo a node value (not atribute)
Cakephp Not validating data in Form
Regex Substring Negation