firasdib / Regex101

This repository is currently only used for issue tracking for www.regex101.com
3.26k stars 199 forks source link

incorrect substitute in PHP for adding new line #1950

Closed jszczypk closed 1 year ago

jszczypk commented 1 year ago

Bug Description

When trying to add new line character using substitution incorrect code is generated for PHP because substitution string is incorrectly escaped - should be using double quotes instead of single quotes.

Reproduction steps

flavor: PHP (any) function: Substitution regular expression: \| test string a|b substitution: \n

Preview shows correctly

a
b

Generated code

$re = '/\|/m';
$str = 'a|b';
$subst = '\\n';

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

Output of generated code

The result of the substitution is a\nb

Expected Outcome

Generated code

$re = '/\|/m';
$str = 'a|b';
$subst = "\n";

$result = preg_replace($re, $subst, $str);

echo "The result of the substitution is ".$result;

Output of generated code

The result of the substitution is a
b
OnlineCop commented 1 year ago

Tested this on onlinephp.io:

    <?php
    $re = '/\|/m';
    $str = 'a|b';
    $subst_bad = '\\n';
    $subst_good = "\n";

    $result_bad = preg_replace($re, $subst_bad, $str);
    $result_good = preg_replace($re, $subst_good, $str);

    echo "The result of the bad substitution is \"".$result_bad."\"";
    echo "\n";
    echo "The result of the good substitution is \"".$result_good."\"";

Result:

The result of the bad substitution is "a\nb"
The result of the good substitution is "a
b"
firasdib commented 1 year ago

Thank you, I will change the quotes to double quotes for the substitution text.