简体   繁体   中英

PHP RegEx - how do I extract matches from a string?

Say I have the following string:

BlahBlah........1.000
Whatevah....2.000
Something......6.500

...that is, some text, followed by four or more dots, followed by a number (that may have a dot as a delimiter) followed by a newline (Linux or Windows, I don't know if that's important). It's a part of a larger string.

How do I extract the text and numbers into variables? More precisely an array of value pairs (array of arrays). I just can't get my head around regular expressions yet... :(

use this regex:

(?<word>\w+)\.+(?<number>\d+(\.\d+)?)

with preg_match_all() :

preg_match_all("/(?<word>\w+)\.+(?<number>\d+(\.\d+)?)/", $yourString, $theArrayYouWantToStoreMatchesInIt);

To capture anything after 4 dots you can use this :

(?<word>\w+)\.{4,}(?<anything>.*)

The following will also capture strings that have spaces in their first part:

(?<beforeDots>[^\.]+)\.{4,}(?<afterDots>.*)

It's also a good idea to limit the matching text to certain range of characters to make the regex more accurate:

(?<beforeDots>[a-zA-Z0-9 ]+)\.{4,}(?<afterDots>[a-zA-Z0-9\. ]+)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM