简体   繁体   English

如何在 PHP 中使用 preg_replace 用元字符替换表达式?

[英]How do i replace an expression with metacharacters using preg_replace in PHP?

I've tried in different ways, replacing a excerpt of text with metacharacters with another text with metacharacters in PHP.我尝试了不同的方法,用 PHP 中的另一个带有元字符的文本替换带有元字符的文本摘录。 I know, it seems very simple but i've tried many times but didn't get it.我知道,这看起来很简单,但我已经尝试了很多次但没有得到它。

pattern: $Sel = 'anyvalues';模式: $Sel = 'anyvalues';

replacement: $Sel = 'one other';替换: $Sel = 'one other';

subject: <?php $Sel = 'anyvalues';主题: <?php $Sel = 'anyvalues';

I deeply tried using addslashes() and preg_quote() methods in different orders but it doesn't work.我试过以不同的顺序使用 addslashes() 和 preg_quote() 方法,但它不起作用。 I need it to be as represented instead of looking for any workarounds.我需要它被代表而不是寻找任何解决方法。

Each one of these values lie in different files, ie, the pattern lies in one file, replacement in another one, and subject also in another.这些值中的每一个都位于不同的文件中,即模式位于一个文件中,替换位于另一个文件中,而主题也位于另一个文件中。

Have you wrapped your pattern in delimiters ?你有没有用 分隔符包装你的模式?

$pattern = '$Sel = "anyvalues_containing_delimiter_/";';
$replacement = '$Sel = "one other";';
$subject = '<?php $Sel = "anyvalues_containing_delimiter_/";';

echo preg_replace(sprintf('/%s/', preg_quote($pattern, '/')), $replacement, $subject);

The contents of pattern are the only ones that need escaping, hence the preg_quote call. pattern 的内容是唯一需要转义的内容,因此调用preg_quote Second argument is the delimiter in which the pattern is wrapped (what sprintf does here), so any occurences within the pattern content can also be escaped before they are applied.第二个参数是包装模式的分隔符( sprintf在这里所做的),因此模式内容中的任何出现也可以在应用之前进行转义。

Edit: I've modified the snippet to cover for occurences of the delimiter within file contents.编辑:我修改了代码片段以涵盖文件内容中分隔符的出现。

Second edit: moved code from linked snippet into the answer itself.第二次编辑:将代码从链接片段移至答案本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM