php regex find text within parenthesis -


using php or powershell need in finding text in text file.txt, within parenthesis output value.

example:

file.txt looks this:

this test (mytest: test) in parenthesis     testing (mytest: johnsmith) again. not testing testing (mytest: 123)  

my code:

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

output new text file be:

123test, johnsmith,123, 

use pattern:

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

note %s here not part of actual pattern. it's used sprintf() substitute values passed arguments. %s stands string, %d signed integer etc.

explanation:

  • ~ - starting delimiter
  • \( - match literal (
  • %s - placeholder $needle value
  • : - match literal :
  • \s* - 0 or more whitespace characters
  • (.*?) - match (and capture) inside parentheses
  • \) - match literal )
  • ~ - ending delimiter
  • s - pattern modifier makes . match newlines 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


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -