Author: Jonas Bilinkevicius
I am attempting to create a file from a title of a webpage. The title can contain
illegal filename characters such as \ / : ? etc. What is the best way to filter out
these characters? I want to remove them entirely, and not replace them with a
space. Thus, I would like to keep alphanumeric, dashes, underscores, space, and a
few other special characters only.
Answer:
Solve 1:
Something like the function below would do. In my code, the function replaces dodgy
chars with a replacement, but I guess it would still work if you specificed the
'CunfriendlyReplacement' as an empty string.
1 { ... }
2 const
3 {$IFDEF WIN32}
4 CpathDelimiter = '\';
5 {$ELSE}
6 CpathDelimiter = '/';
7 {$ENDIF}
8 CdelimiterChar = '_';
9 CunfriendlyChars = [CpathDelimiter, '.', ':', CdelimiterChar, '/', '<', '>', '|'];
10 CunfriendlyReplacement = '-';
11 { ... }
12
13 function makeNameFileFriendly(const inName: string): string;
14 var
15 charIndex: Integer;
16 thisChar: Char;
17 begin
18 result := '';
19 for charIndex := 1 to length(inName) do
20 begin
21 thisChar := inName[charIndex];
22 if (thisChar in CunfriendlyChars) then
23 result := result + CunfriendlyReplacement
24 else
25 result := result + thisChar;
26 end;
27 end;
Solve 2:
28 function ValidateFilename(Filename: WideString): WideString;
29 var
30 i: Integer;
31 begin
32 Result := '';
33 for i := 1 to Length(Filename) do
34 begin
35 if Pos(Filename[i], WideString('\/:*?<>|,' + #34)) = 0 then
36 Result := Result + Filename[i];
37 end;
38 Result := Trim(Result);
39 end;
Solve 3:
40 uses
41 SysUtils;
42
43 const
44 cIllegalChars: tSysCharSet = ['\', '/', '?', '*', '.'];
45
46 var
47 i, j: integer;
48
49 { ... }
50 SetLength(result, Length(Filename));
51 j := 0;
52 for i := 1 to Length(Filename) do
53 begin
54 if not (Filename[i] in cIllegalChars) then
55 begin
56 inc(j);
57 result[j] := Filename[i];
58 end;
59 end;
60 SetLength(result, j);
61 { ... }
|