import re


def replace(string, substitutions):
    """ Perform many string replacements
    all at once.

    Parameters
    ----------
    string : str
        The string to modify.
    substitutions : dict of str to str
        The string replacements to perform.

    Returns
    -------
    str
        The modified string.

    Examples
    --------
        >>> qosy.tools.replace('ABC', {'A':'AB', 'B':'D', 'C':'AC'}) # 'ABDAC'
    """
    
    # From https://gist.github.com/carlsmith/b2e6ba538ca6f58689b4c18f46fef11c
    
    substrings = sorted(substitutions, key=len, reverse=True)
    regex      = re.compile('|'.join(map(re.escape, substrings)))

    return regex.sub(lambda match: substitutions[match.group(0)], string)