John Davidson

php - Unable to replace `$_` by something else in preg_replace()

0 comments
Message:


I am investigating, but I am not able to find the solution to this.


The idea is to replace the characters $_ from a string with something else.
If you remove the dollar sign from the $search variable, it kind of works (but not in a desirable way).


It is not working because the dollar sign is a special character, but I cannot find how to scape it.


This is what I have:


$search = '$_'; // replace to '_' OR '[$_]' it returs "$1" instead of "1"
$replace = 1;
$regex = '#".*?"(*SKIP)(*FAIL)|\b' . $search . '\b#s';

$fullInput = '"$_" $_';

$r = preg_replace([$regex], $replace, $fullInput);

echo $r . PHP_EOL;

// Output with current code : "$_" $_
// Output with '_' or '[$_]': "$_" $1
//
// Expected result: "$_" 1


To have into account, if the text is between quotes, it should not be replaced.




My Answer:
null
$replace = '_';
$string = 'This is a $_ test string';

$new_string = preg_replace('/' . preg_quote($search, '/') . '/', $replace, $string);

echo $new_string; // Output: This is a _ test string

Rate this post

3 of 5 based on 5543 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us