-1

Using PHP or Powershell I need help in finding a text in a text file.txt, within parenthesis then output the value.

Example:

file.txt looks like this:

This is a test I (MyTest: Test) in a parenthesis
    Another Testing (MyTest: JohnSmith) again. Not another testing testing (MyTest: 123) 

My code:

$content = file_get_contents('file.txt'); 
   $needle="MyTest"
preg_match('~^(.*'.$needle.'.*)$~', $content, $line);

Output to a new text file will be:

123Test, JohnSmith,123,
5
  • What does $needle contain? Commented Apr 14, 2014 at 14:23
  • my needle is "MyTest" however,i couldn't get the values following it. Commented Apr 14, 2014 at 14:23
  • You should use preg_quote($needle) to ensure any text your injecting into the regex gets escaped properly. Commented Apr 14, 2014 at 14:24
  • Don't forget to put a semi-colon at the end of $needle="MyTest" @Menew Commented Apr 14, 2014 at 14:26
  • where does the 123Test come from in the example output? Commented Apr 14, 2014 at 14:32

2 Answers 2

7

Use this pattern:

~\(%s:\s*(.*?)\)~s

Note that %s here is not a part of the actual pattern. It's used by sprintf() to substitute the values that are passed as arguments. %s stands for string, %d for signed integer etc.

Explanation:

  • ~ - starting delimiter
  • \( - match a literal (
  • %s - a placeholder for the $needle value
  • : - match a literal :
  • \s* - zero or more whitespace characters
  • (.*?) - match (and capture) anything inside the parentheses
  • \) - match a literal )
  • ~ - ending delimiter
  • s - a pattern modifier that makes . match newlines as well

Code:

$needle  =  'MyTest';
$pattern = sprintf('~\(%s:\s*(.*?)\)~s', preg_quote($needle, '~'));
preg_match_all($pattern, $content, $matches);
var_dump($matches[1]);

Output:

array(3) {
  [0]=>
  string(4) "Test"
  [1]=>
  string(9) "JohnSmith"
  [2]=>
  string(3) "123"
}

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

Here's a Powershell solution:

@'
This is a test I (MyTest: Test) in a parenthesis
    Another Testing (MyTest: JohnSmith) again. Not another testing testing (MyTest: 123) 
'@ | set-content test.txt


([regex]::Matches((get-content test.txt),'\([^:]+:\s*([^)]+)')|
 foreach {$_.groups[1].value}) -join ','

Test,JohnSmith,123

You can add that trailing comma after it's done if you really did want that there....

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.