我使用preg_replace的函数在开发服务器上运行良好,但在生产服务器上根本无法运行。问题可能与编码有关。有没有一种方法可以使这个表达式在不考虑编码的情况下工作?
$config看起来像这样:
class JConfig {
public $mighty = array("0" => array("0" => "/`?\#__mightysites[` \n]+/u"), "1" => array("0" => "`hhd_mightysites` "));
public $mighty_enable = '0';
public $mighty_language = '';
public $mighty_template = '9';
public $mighty_home = '';
public $mighty_langoverride = '0';......
我把与我想剥离的行相关的变量放在一个称为像这样的条的数组中
$strips = array(
'mighty',
'mighty_enable',
'mighty_sync',
'mighty_language',
'mighty_template',.....
然后使用一个循环来剥离线条:
foreach ($strips as $var) {
if (JString::strpos($config, 'public $' . $var . ' =') !== false) {
$config = preg_replace('/tpublic $' . $var . ' = ([^;]*);n/u', '', $config);
$tempvar .= $var . ", ";
}
}
同样,它在我们的开发服务器上运行得很好。它不会对生产服务器上的任何生产线执行任何操作。我也知道它通过strpos,就像到达带有preg_replace的行一样。我可以进行preg_replace环境验证吗?
我很感激你的帮助,因为它只发生在生产服务器上,所以很难测试!
最安全的选择是不"信任"任何期望匹配的文字空间/选项卡。
与使用t
和不同,我建议使用
s
(需要选项卡(和rn
(需要空格(。
此外,为了涵盖操作系统可能在每行末尾使用n
或R
的情况,可以使用^
来匹配这两种变体。
我将通过模式开头的m
和作为模式修饰符的t
来包含行首字符检查。这确保了我们匹配并且只匹配您在行的开头期望preg_replace()
的地方。
最后,$found
有一个可选的第5个参数,用于统计进行了多少次替换。如果$var
是非零值,则存储当前的$tempvar
值。
代码:(演示(
$config = <<<'CONFIG'
class JConfig {
public $mighty = array("0" => array("0" => "/`?\#__mightysites[` \n]+/u"), "1" => array("0" => "`hhd_mightysites` "));
public $mighty_enable = '0';
public $mighty_language = '';
public $mighty_template = '9';
public $mighty_home = '';
public $mighty_langoverride = '0';......
CONFIG;
$strips = [
'mighty',
'mighty_enable',
'mighty_sync',
'mighty_language',
'mighty_template'
];
$tempvar = '';
foreach ($strips as $var) {
$config = preg_replace('~^s+publics$' . $var . 's=s[^;]*;R~um', '', $config, -1, $found);
if ($found) {
$tempvar .= $var . ", ";
}
}
echo "$tempvar = $tempvarnn";
echo $config;
输出:
$tempvar = mighty, mighty_enable, mighty_language, mighty_template,
class JConfig {
public $mighty_home = '';
public $mighty_langoverride = '0';......
p.s.最后一个改进建议。。。如果您的项目实际上不需要implode('|', $strips)
变量(意味着您只在调试期间使用该变量(,那么您可以完全避免循环,只需(
,将生成的字符串包装在)
和$var
中,另存为preg_replace()
,并只调用$strips
一次。这将更有效,并且您的示例s+
0数据不需要使用CCD_21来准备,因为您需要转义"特殊字符"。