preg_replace PHP 在一些引号之间
preg_replace PHP between some quotes
我对 preg_replace 有点困惑,因为我以前没有使用过正则表达式。
我进行了一些搜索,但找不到适合我情况的任何内容。
我有包含与服务器建立的连接的日志,如下所示:
Username connected, address "123.123.123.123:1234"
我要preg_replace寻找这部分:
address "123.123.123.123:1234"
并将其更改为:
address "snip"
基本上是剪掉了IP地址,这样这些日志就可以在网站上公开发布了。
这是我目前正在测试的内容。
$new_log = preg_replace('/\address\s"(.*)"/', '', $old_log);
我只是需要帮助让正则表达式正确。
这应该适合你:
(这里我将文件的所有行放入一个数组 file()
. After this I replace the part address "[ip]"
with address "snip"
with preg_replace()
. At the end I just save the array again in the file with file_put_contents()
)
<?php
$lines = file("logs.txt");
$lines = preg_replace("/\baddress\s?\".*?\"/", "address \"snip\"", $lines);
file_put_contents("logs.txt", $lines);
?>
正则表达式解释:
\baddress\s?\".*?\"
- \b 在单词边界断言位置 (^\w|\w$|\W\w|\w\W)
- 地址字面匹配字符地址(区分大小写)
- \s? 匹配任意白色 space 字符 [\r\n\t\f ]
- 量词:?零到一次之间,尽可能多次,按需回馈[贪心]
- \" 匹配字符 " literally
- .*? 匹配任何字符(换行符除外)
- 量词:*?零次和无限次之间,次数越少越好,按需扩充[懒惰]
- \" 匹配字符 " literally
之前的示例文件:
Username connected, address "123.123.123.123:1234"
Username connected, address "123.123.123.123:1234"
之后:
Username connected, address "snip"
Username connected, address "snip"
旁注:
如果您想阅读更多关于正则表达式的内容,还有一些有用的链接:
我对 preg_replace 有点困惑,因为我以前没有使用过正则表达式。 我进行了一些搜索,但找不到适合我情况的任何内容。
我有包含与服务器建立的连接的日志,如下所示:
Username connected, address "123.123.123.123:1234"
我要preg_replace寻找这部分:
address "123.123.123.123:1234"
并将其更改为:
address "snip"
基本上是剪掉了IP地址,这样这些日志就可以在网站上公开发布了。
这是我目前正在测试的内容。
$new_log = preg_replace('/\address\s"(.*)"/', '', $old_log);
我只是需要帮助让正则表达式正确。
这应该适合你:
(这里我将文件的所有行放入一个数组 file()
. After this I replace the part address "[ip]"
with address "snip"
with preg_replace()
. At the end I just save the array again in the file with file_put_contents()
)
<?php
$lines = file("logs.txt");
$lines = preg_replace("/\baddress\s?\".*?\"/", "address \"snip\"", $lines);
file_put_contents("logs.txt", $lines);
?>
正则表达式解释:
\baddress\s?\".*?\"
- \b 在单词边界断言位置 (^\w|\w$|\W\w|\w\W)
- 地址字面匹配字符地址(区分大小写)
- \s? 匹配任意白色 space 字符 [\r\n\t\f ]
- 量词:?零到一次之间,尽可能多次,按需回馈[贪心]
- \" 匹配字符 " literally
- .*? 匹配任何字符(换行符除外)
- 量词:*?零次和无限次之间,次数越少越好,按需扩充[懒惰]
- \" 匹配字符 " literally
之前的示例文件:
Username connected, address "123.123.123.123:1234"
Username connected, address "123.123.123.123:1234"
之后:
Username connected, address "snip"
Username connected, address "snip"
旁注:
如果您想阅读更多关于正则表达式的内容,还有一些有用的链接: