Regular expression help, not finding what I need
I'm a rookie trying to search a text file for some serial numbers. I'm using PHP 5 and I am reading out of a CSV file. I have created the following regular expression:
/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/
I'm looking through a rather large text file for serial numbers that resemble the one listed below:
37DB4B71-DAFA-4311-9AC6-0005646CB9BC
It always finds the first serial number, but it does not find any of the others. There are at least 15 others, any suggestions on what I’m doing wrong? It was my impression that \w will find either a number or digit in-case sensitive. I figured it worked as it found the first instance.
Here is the code I am using to parse the CSV file, I'm just bringing the whole file in and trying to split it into an array by serial number. Below is the code I am using to see if I can at least get the serial numbers split before I do anything else. Right now it shows me an array with开发者_如何学C 1 item inside. That one item is the serial number followed by a bunch of text and the serial numbers I need.
One more thing, the reason I'm using preg_split is because the serial number is followed by a comma and then some details about the serial number. I was trying to use Preg_split to break the file so the text would follow the serial number.
$searchPattern = '/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/';
//Get the contents of the File
$contents = file_get_contents('C:/files/andrew1.csv');
if ($contents === false){
echo 'Sorry, there was a problem reading the file.';
} else{
$NoHTMLContents = strip_tags($contents);
$splitContents = preg_split($searchPattern, $NoHTMLContents);
echo '<pre>';
print_r($splitContents);
echo '</pre>';
}
It would help if you posted your code, but I'm guessing that you need to use preg_match_all
instead of preg_match
as the latter only returns the first match.
You should also remember to use the PCRE_MULTILINE pattern modifier (m):
preg_match_all('/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/m', $s, $matches);
See it working online: ideone
For a preg_split based approach, try using a lookahead:
$matches = preg_split("/\n(?=\w{8}-\w{4}-\w{4}-\w{4}-\w{12})/m", $s);
See it working online: ideone
I just tested your regular expression and your serial number matches. You can use this online tester of PHP preg_match. It would be good if you post the other serial numbers and if you do something like i
at the end to specify ignoring case,
$regex = "/^\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/i";
精彩评论