问题
I have a file in this format:
5:Name: {"hash":"c602720140e907d715a9b90da493036f","start":"2016-02-20","end":"2016-03-04"}
5:Name: {"hash":"e319b125d71c62ffd3714b9b679d0624","sa_forum":"on","start":"2015-11-14","end":"2016-02-20"}
I am trying to extract the hash key and date using a regular expression. How can I do it?
I tried this /^[a-z0-9]{32}$/
for the hash but it doesn't work.
I would appreciate some help.
Edit: This is a text file, and I'm trying to preg_match()
it. Here's my code:
$file = file_get_contents("log.txt");
preg_match("/^[a-z0-9]{32}$/",$file, $hashes);
var_dump($hashes);
I get an empty array.
回答1:
The problem is that you're bounding your match with ^
and $
, but you actually want to match something in the middle of the string. Try this:
/(?<=")[a-f0-9]{32}(?=")/
This will only match between the quotes. Also, you don't need a-z
as it can only be a-f
.
Also, since you want an array of all of the hashes in the file and not just one, you need preg_match_all():
php > $file = file_get_contents("hashfile.txt");
php > preg_match_all('/(?<=")[a-f0-9]{32}(?=")/', $file, $matches);
php > var_dump($matches);
array(1) {
[0]=>
array(2) {
[0]=>
string(32) "c602720140e907d715a9b90da493036f"
[1]=>
string(32) "e319b125d71c62ffd3714b9b679d0624"
}
}
php >
The matches are stored in the array $matches[0]
in my above example.
来源:https://stackoverflow.com/questions/35530010/regular-expression-to-extract-hashes-from-file