简体   繁体   中英

Perl Search and replace keeping middle part of string

I've been using Codeigniter for my PHP project and I've been using their session class.

$this->session->userdata('variablename')

I've been having a lot of problems with this so i've decided to use PHP Native session.

$_SESSION['variablename']

This is what I've got so far

perl -p -i -e "s/$this->session->userdata('.*?$SOMEVAR.*?\')/$_SESSION['$1']/g" offer.php 

But truth to be told I don't really know what I'm doing.

I would also like to do this on all php files in my project.

Help much appreciated.

The regex should be:

s/\\$this->session->userdata\\('(.?)'\\)/$_SESSION['$1']/g

Issues with the version you posted are mostly with un-escaped characters--you can escape a $ or parenthesis by adding a \\ prior to the character. For example, \\$this will find the text "$this", while $this will search for the value of the $this variable.

For a more comprehensive look at escapes (and other quick tips), if you have $2, I highly recommend this cheat sheet .

Also, you don't need to use the .*?$SOMEVAR.*? construct you added in there...Perl will automatically capture the result found between the first pair of parentheses and store it in $1 , the second set of parentheses gets $2 , etc.

When shell quoting is getting complicated, the simplest thing to do is to just put the source into a file. You can still use it as a one-liner. I have used a negative lookahead assertion to make sure that it does not break for escaped single quotes inside the string.

# source file, regex.txt
s/\$this->session->userdata\('(.+?)(?!\\')'\)/\$_SESSION['$1']/g;

Usage:

perl -pi regex.txt yourfile.php

Note that you simply leave out the -e switch. Also note that -i requires a backup extension for Windows, eg -i.bak .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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