简体   繁体   中英

Convert function PHP to C#

I am stuck in a convertion of PHP function to C#!

Someone can tell me what I am doing bad?

Original code (PHP):

function delete_all_between($beginning, $end, $string)
{
    $beginningPos = strpos($string, $beginning);
    $endPos = strpos($string, $end);
    if ($beginningPos === false || $endPos === false) {
        return $string;
    }

    $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos);

    return str_replace($textToDelete, '', $string);
}

My code C#:

string delete_all_between(string beginning, string end, string html)
{
    int beginningPos = html.IndexOf(beginning);
    int endPos = html.IndexOf(end);
    if (beginningPos == -1 || endPos == -1)
    {
        return html;
    }
}

I hope someone can help me, I am really stuck!

Use Substring and Replace to mask out and replace the unwanted string. Also, I would add a check to make sure that endPos > beginningPos :

string delete_all_between(string beginningstring, string endstring, string html)
{
    int beginningPos = html.IndexOf(beginningstring);
    int endPos = html.IndexOf(endstring);
    if (beginningPos != -1 && endPos != -1 && endPos > beginningPos) 
    {
        string textToDelete = html.Substring(beginningPos, (endPos - beginningPos) + endstring.Length); //mask out
        string newHtml = html.Replace(textToDelete, ""); //replace mask with empty string
        return newHtml; //return result
    }
    else return html; 
}

Test with input

delete_all_between("hello", "bye", "Some text hello remove this byethat I wrote")

Yields the result:

Some text that I wrote

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