I am a student developing an application which takes the contents of a PHP file and stores them to a variable.
The user will input what characters/values need to be replaced in the loaded content.
For example :
FIND REPLACE
echo Print
<?php <?
CURL (space)
These patterns then can be saved to a text file for further use. When the user wants to remove the content according to the pattern, they can do so by clicking a button.
So my question is :
Can this be easily archived via a basic string replace method, or should I go for a more complex regex?
And if I should use regex, how can I create custom regex patterns based on user input?
I'll be very grateful if you can help me with this, thank you.
This can be achieved using simply Replace
, a Regex to handle such elaborate requirements would not only be messy, but incredibly difficult to maintain/update with additional items.
How about storing your Find and replace patterns in a Dictionary
and then looping through and doing the replace? That way, if you add more items, you just need to add them to your Dictionary
. Something like:
Dictionary<string, string> replacements = new Dictionary<string, string>
{
{ "echo", "PRINT" },
{ "<?php", "<?" },
{ "CURL", "(space)" }
}
string yourString; //this is your starter string, populate it with whatever
foreach (var item in replacements)
{
yourString = yourString.Replace(item.Key, item.Value);
}
If you are simply trying to replace a set of characters in a given string with another set of characters, then the string.Replace()
method will suit you just fine.
The goal of any programmer should be to write the simplest possible code for a given task. While regexes are well suited to contextual replacements, if all you need is basic find and replace functionality then they are definitely overkill and will only serve to introduce unnecessary complexity into your program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With