douyunjiaok300404 2015-07-26 23:27
浏览 81
已采纳

带有变量输入的preg_replace

I'm quite new to this, and have borrowed some code from another post I found, I don't know if what I am trying to do is the right or the best way, its just how I am "getting" it to work..

This is the code

<?php
$yn = $_POST['YN'];
echo $yn;
$fl='config.php'; 
        /*read operation ->*/ $tmp = fopen($fl, "r");   $content=fread($tmp,filesize($fl)); fclose($tmp);

// here goes your update
$content = preg_replace('/\$yourname = \"(.*?)\";/', '$yourname = ""$YN"";', $content);


        /*write operation ->*/ $tmp =fopen($fl, "w");    fwrite($tmp, $content);    fclose($tmp);
?>

I am trying to update a config file entry that matches $yourname with the POST result, I can echo $yn and it contains the correct value, but I can't get the variable to work in the regex replace,

$content = preg_replace('/\$yourname = \"(.*?)\";/', '$yourname = ""$yn"";', $content);

so if $yn = karl then im trying to update $yourname = "" in the file to $yourname = "karl"

but I can't get it to work, the closest I get is it updating the file with the variable as text, ie $yourname = "$yn".

hope someone can help

  • 写回答

2条回答 默认 最新

  • dthh5038 2015-07-26 23:40
    关注

    I would suggest using a pattern like this

         preg_replace( '/'.preg_quote( $yourname ).'\s*=\s*\"[^\"]+\";/', $yourname.'="'.$yn.'";', $content);
    

    ..'\s*=\s*\"([^\"]+)\";

    • preg_quote( $yourname ) - escaped variable input ( literal match )
    • \s* - one or more spaces
    • = - literal (=)
    • \s* - one or more space
    • \" - literal (")
    • [^\"]+ - match any character not a (") greedy match as many times as possible.
    • \" - literal (")
    • ; literal (;)

    In this case ( because it uses double quotes ), it's (prudent?) better to use concatenation and save the headache of escaping it. No need to be fancy when simplicity will win the day.

    Also be wary of mistakes like this $yn vs $YN in php variable names are case sensitive, without that knowledge it can be a major challenge to find the error, because to us humans it looks the same. Of course it doesn't help that file names, class names, functions and methods are case insensitive ( on Windows ). Really not sure if class and method names are case sensitive on linux, I try to avoid the issue and always use the same casing.

    Seeing as it looks like the OP possibly wanted $yourname ( literally ) I updated the regx

     preg_replace( '/\$yourname\s*=\s*\"[^\"]+\";/', '$yourname="'.$yn.'";', $content);
    

    https://regex101.com/r/yM9cX9/1

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 asp.textbox后台赋值前端不能显示什么原因
  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误