ThisIsMyUsername
ThisIsMyUsername

Reputation: 11

Extract multiple lines of text from string PHP

I have a string of registry keys that looks like this:

ThreatName REG_SZ c:\temp Protection Code REG_SZ a Check ThreatName REG_SZ c:\windows Protection

I want to extract "c:\WHATEVER" from the string. It occurs multiple times between the words "ThreatName REG_SZ" and "Protection".

How can I extract "c:\WHATEVER" multiple times using PHP?

Upvotes: 1

Views: 925

Answers (1)

Jim
Jim

Reputation: 18853

One way to do it is using Regular Expressions, here is an example code (un-tested).


$string = "ThreatName REG_SZ c:\\temp Protection
Code REG_SZ c:\\a Check
ThreatName REG_SZ c:\\windows Protection";

preg_match_all("~.* REG_SZ (.*) ~iU", $string, $matches);

print_r($matches);

If you want to understand more see the php manual for: preg_match_all(). Or google regular expressions for more information on them. But basically it looks between the REG_SZ and Protection (the U modifier makes it ungreedy so it will look for the first Protection) and returns everything but the new line character (the .*). If this is spread across new lines, the 's' modifier will help resolve that.

EDIT: Saw that you wanted them all. This should work for all of them.

EDIT: Fixed the regex to include "ThreatName", not sure if this is dynamic. Also added extra slashes to the string as they were being parsed as characters.

I am not sure if you will have to use addslashes() on the string or not, but it maybe needed.

Removed the isset as it was not necessary.

EDIT: Modified the code given that the correct output formatting was omitted. The updated method will work, but if the directory has a space in it, chances are it will only pull the first part of the directory.

Upvotes: 1

Related Questions