NUL*_*ULL 0 php regex powershell
使用PHP或Powershell我需要帮助在文本file.txt中查找文本,在括号内输出值.
例:
file.txt 看起来像这样:
This is a test I (MyTest: Test) in a parenthesis
Another Testing (MyTest: JohnSmith) again. Not another testing testing (MyTest: 123)
Run Code Online (Sandbox Code Playgroud)
我的代码:
$content = file_get_contents('file.txt');
$needle="MyTest"
preg_match('~^(.*'.$needle.'.*)$~', $content, $line);
Run Code Online (Sandbox Code Playgroud)
输出到新的文本文件将是:
123Test, JohnSmith,123,
Run Code Online (Sandbox Code Playgroud)
使用此模式:
~\(%s:\s*(.*?)\)~s
Run Code Online (Sandbox Code Playgroud)
请注意,%s这不是实际模式的一部分.它用于sprintf()替换作为参数传递的值.%s代表字符串,%d用于有符号整数等.
说明:
~ - 开始分隔符\( - 匹配文字 (%s- $needle值的占位符: - 匹配文字 :\s* - 零个或多个空白字符 (.*?) - 匹配(和捕获)括号内的任何内容\) - 匹配文字 )~ - 结束分隔符s- 一个模式修饰符,也可以.匹配换行符码:
$needle = 'MyTest';
$pattern = sprintf('~\(%s:\s*(.*?)\)~s', preg_quote($needle, '~'));
preg_match_all($pattern, $content, $matches);
var_dump($matches[1]);
Run Code Online (Sandbox Code Playgroud)
输出:
array(3) {
[0]=>
string(4) "Test"
[1]=>
string(9) "JohnSmith"
[2]=>
string(3) "123"
}
Run Code Online (Sandbox Code Playgroud)