John Davidson

php - Dynamically replace part of a condition block with regex

0 comments
Message:


There is a string in format:


else if($rule=='somerule1')
echo '{"s":1,"n":"name surname"}';
else if($rule=='somerule2')
echo '{"s":1,"n":"another text here"}';
...

"s" can have only number, "n" any text.


In input I have $rule value, and I need to remove the else if block that corresponds to this value. I am trying this:


$str = preg_replace("/else if\(\$rule=='$rule'\)\necho '{\"s\":[0-9],\"n\":\".*\"/", "", $str); 

where $str is a string, that contains blocks I mentioned above, $rule is a string with rule I need to remove. But the function returns $str without changes.


What do I do wrong?




For example, script to change "s" value to 1 works nice:


$str = preg_replace("/$rule'\)\necho '{\"s\":[0-9]/", $rule."')\necho '{\"s\":1", $str);

So, probably, I am doing mistake with = symbol, or maybe with space, or with .*.



My Answer:
$rule = 'somerule1';
$string = "else if(\$rule=='somerule1') echo '{';";

$replacement = "else if(\$rule=='replacementrule') echo '{';";

$newString = preg_replace("/else if\(\$rule=='\w+'\)/", $replacement, $string);

echo $newString;

Rate this post

3 of 5 based on 2626 votes

Comments




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