dongliping003116 2019-05-03 13:44
浏览 45
已采纳

如何使用正则表达式在PHP代码中捕获不带引号的数组索引并引用它们?

PHP 7.2 upgraded undefined constant errors from a notice to a warning, with advice that in future they will return a full-on error instead.

I am trying to identify a way to fix these via scripting, ideally via a regex that I can run to parse each PHP file on a site, find all offending bits of code, and fix them.

I've found multiple examples of how to fix one variant, but none for another, and it's that one that I'm looking for help with.

Here's an example file:

<?php

$array[foo] = "bar"; 
// this should become 
// $array['foo'] = "bar"

echo "hello, my name is $array[foo] and it's nice to meet you"; 
// would need to become 
// echo "hello, my name is " . $array['foo'] . " and it's nice to meet you";

?>

I've seen a lot of options to identify and change the first type, but none for the second, where the undefined constant is within a string. In that instance the parser would need to:

  1. Replace $array[foo] with $array['foo']
  2. Find the entire variable, end quotes beforehand, put a . either side, and then reopen quotes afterwards

Edit: ideally one regexp would deal with both examples in the sample code in one pass - i.e. add the ticks, and also add the quotes/dots if it identifies it’s within a string.

  • 写回答

2条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 运行WGCNA代码时出现Error in merge$colors : object of type 'closure' is not subsettable
      • ¥15 C#winform 关掉当前界面,返回到上一界面,但不重新创建
      • ¥15 Multisim14.0软件安装
      • ¥15 一块GD32F105芯片的主板。怎么找RXD和TXD串口
      • ¥15 磁盘异常导致工业相机GigE传图卡顿
      • ¥20 python中使用chatgpt为什么一直连接失败
      • ¥50 使用grpc遇到的问题
      • ¥100 运算速度优化问题,控制在四秒以内
      • ¥15 如何用matlab画出这样的图
      • ¥15 线性回归问题进行特征缩放后,为什么求得的参数不对了