AllThisOnAnACER
AllThisOnAnACER

Reputation: 331

Regex search with wildcard and insert

I have thousands of lines of code that need an adjustment: Currently they look like this:

htmlentities($row_author['Book_ID'])
htmlentities($_GET['BookTitle'])

etc. For internationalization, I need them to include ENT_COMPAT, 'utf-8'

htmlentities($row_author['Book_ID'], ENT_COMPAT, 'utf-8')
htmlentities($_GET['BookTitle'], ENT_COMPAT, 'utf-8')

I have looked all morning for a regex that would let me search and insert the , ENT_COMPAT, 'utf-8' part to the end of the existing code, but regex is 'through the looking glass' for me and I could use some pointers.

I used .* to find all of them, but the insert of the ENT_COMPAT is tricky.

Thank you for any help you can offer. The correct answer will be Checked.

Upvotes: 0

Views: 55

Answers (3)

anubhava
anubhava

Reputation: 785316

You can use this recursive regex for search:

'^(\s*htmlentities\s*)( \( (?: [^()]* | (?2) )* \) )/mx'

RegEx Demo

CODE

$input = "htmlentities(trim(\$_GET['BookTitle']))";
$result = preg_replace_callback('/^(\s*htmlentities\s*)( \( (?: [^()]* | (?2) )* \) )/mx',
    function ($m) { return $m[1] . substr($m[2], 0, strrpos($m[2], ')')) .
       ', ENT_COMPAT, "utf-8")'; }, $input);
echo $result;
//=> htmlentities(trim($_GET['BookTitle']), ENT_COMPAT, "utf-8")

Upvotes: 2

Bohemian
Bohemian

Reputation: 425098

Assuming an editor, you need a search and replace:

Search:  htmlentities\(\$\w+\[.*?\]
Replace: $0, ENT_COMPAT, "utf-8"

Depending on your editor "$0" may need to be "\0".

Upvotes: 1

vks
vks

Reputation: 67968

  (.*?\])

Try this.

Replacement string will include your added characters.

See demo.

http://regex101.com/r/dD3nI1/1

Upvotes: 3

Related Questions