简体   繁体   中英

Regular expression to escape line breaks in a string

I have a string in PHP that contains Python code, like below:

$source_code = "\nprint('Hello\nWorld')\n";

I need to escape line breaks between single or double quotes. I want to get something like the following:

$source_code = "\nprint('Hola\\nWorld')\n";

In other words, simply precede with an \ any occurrence of \n that is contained within single or double quotes. I have this in PHP for now in case single quotes are found:

<?php
    $source_code = "\nprint('Hello\nWorld')\n";
    $source_code = preg_replace("/'(.*)(\\n)(.*)'/", "\\n", $source_code);
    echo $source_code;
?>

But I am getting: \nprint(\n)\n . However, the expected string should be: \nprint('Hello\\nWorld')\n .

Thanks in advance!

you can use twice replacement, the first is remove the both ends "\n", and then replace the center \n

Works for single strings only. Feel free to extend if neccessary.

$source_code = "x=input()\nprint('Hello\nWorld')\n"; // thx for the test @Hugo :)

$match = preg_match('/(["\'])(.*)\1/s', $source_code, $matches);

if ($match) {
    $text = $matches[2];
    $text = str_replace("\n", '\\\\n', $text);
    $source_code = preg_replace('/(.*)((["\']).*\3)(.*)/s', '$1$3' . addslashes($text) . '$3$4', $source_code);
}

var_dump($source_code);

Wokring example .

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