Txt-Search replace

From Vectorlab

Jump to: navigation, search


Function to search replace a string. By Orso B. Schmid


{ Orso *********************************************** }
{ search replace in a given string }
{ warning! this can output an empty string! }
FUNCTION T_SearchReplace(sourceStr, searchStr, replStr: STRING): STRING;
    VAR
        tempSource, ready : STRING;
        posInStr : INTEGER;
        
    BEGIN
        ready := '';
        tempSource := sourceStr;
            
        { search replacing something like that: 'mmmmm', 'mm', 'mmm'
        produces a nice endless loop without double storing the var }
        
        WHILE (Pos(searchStr, tempSource) > 0) DO BEGIN
        
            { insert Delete was breaking on empty strings }
            IF (searchStr = tempSource) & (replStr = '') THEN
                tempSource := ''
                
            ELSE BEGIN
                posInStr := Pos(searchStr, tempSource);
                
                IF posInStr = 1 THEN
                    ready := Concat(ready, replStr)
                ELSE
                    ready := Concat(ready, Copy(tempSource, 1, posInStr-1), replStr);
                    
                tempSource := Copy(tempSource, posInStr + Len(searchStr), Len(tempSource));
                { even if it's longer than the rest of the string, doesn't matter }
            END;
        END;
        
        T_SearchReplace := Concat(ready, tempSource);
    END;
Personal tools