0

我正在尝试将一个单词替换为一些 php 代码

$filecontent = [regex]::Replace($filecontent, $myword, $phpcode)

但是 $phpcode 有一些使用特殊变量 $_ 的 php 代码

<?php $cur_author = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author)); ?>

问题是,当代码在 $filecontent 中被替换时,它会将 php 代码( $_GET )中的 $_ 变量替换为管道中的变量。

像 $author_name 这样的其他变量不会发生这种情况。

我该如何解决这个问题?

4

3 回答 3

3

你有两个选择。首先使用单引号字符串,PowerShell 会将其视为逐字字符串(C# 术语),即它不会尝试进行字符串插值:

'$_ is passed through without interpretation'

另一种选择是转义$双引号字符串中的字符:

"`$_ is passed through without interpretation"

当我弄乱正则表达式时,我将默认使用单引号字符串,除非我有一个需要在字符串内插值的变量。

另一种可能性是$_正则表达式将其解释为替换组,在这种情况下,您需要在$eg上使用替换转义$$

于 2013-10-25T15:46:24.863 回答
3

Does this work for you?

$filecontent = [regex]::Replace($filecontent, $myword, {$phpcode})

In a regex replace operation the $_ is a reserved substituion pattern that represents the entire string

http://msdn.microsoft.com/en-us/library/az24scfc.aspx

Wrapping it in braces makes it a scriptblock delegate, bypassing the normal regex pattern matching algorithms for doing the replacement.

于 2013-10-25T15:49:29.760 回答
1

我不确定我是否正确地关注你,但这有帮助吗?

$file = path to your file
$oldword = the word you want to replace
$newword = the word you want to replace it with

如果您要替换的旧词有特殊字符(即 \ 或 $ ),那么您必须先转义它们。您可以通过在特殊字符前面放置反斜杠来转义它们。新词,不需要转义。$ 将变为“\$”。

(get-content $file) | foreach-object {$_ -replace $oldword,$NewWord} | Set-Content $file
于 2013-10-25T15:47:14.790 回答