forked from siteserver/cms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringUtils.cs
More file actions
681 lines (603 loc) · 24.3 KB
/
StringUtils.cs
File metadata and controls
681 lines (603 loc) · 24.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
using System;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
namespace SiteServer.Utils
{
public static class StringUtils
{
public static class Constants
{
public const string ReturnAndNewline = "\r\n";//回车换行
public const string Html5Empty = @"<html><head><meta charset=""utf-8""></head><body></body></html>";
public const string Ellipsis = "...";
public const int PageSize = 25;//后台分页数
public const string HideElementStyle = "display:none";
public const string ShowElementStyle = "display:";
public const string TitleImageAppendix = "t_";
public const string SmallImageAppendix = "s_";
}
public static bool IsMobile(string val)
{
return Regex.IsMatch(val, @"^1[3456789]\d{9}$", RegexOptions.IgnoreCase);
}
public static bool IsEmail(string val)
{
return Regex.IsMatch(val, @"^\w+([-_+.]\w+)*@\w+([-_.]\w+)*\.\w+([-_.]\w+)*$", RegexOptions.IgnoreCase);
}
public static bool IsNumber(string val)
{
const string formatNumber = "^[0-9]+$";
return Regex.IsMatch(val, formatNumber);
}
public static bool IsDateTime(string val)
{
const string formatDate = @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$";
const string formatDateTime = @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-)) (20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$";
return Regex.IsMatch(val, formatDate) || Regex.IsMatch(val, formatDateTime);
}
public static bool In(string strCollection, int inInt)
{
return In(strCollection, inInt.ToString());
}
public static bool In(string strCollection, string inStr)
{
if (string.IsNullOrEmpty(strCollection)) return false;
return strCollection == inStr || strCollection.StartsWith(inStr + ",") || strCollection.EndsWith("," + inStr) || strCollection.IndexOf("," + inStr + ",", StringComparison.Ordinal) != -1;
}
public static bool Contains(string text, string inner)
{
return text?.IndexOf(inner, StringComparison.Ordinal) >= 0;
}
public static bool ContainsIgnoreCase(string text, string inner)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(inner)) return false;
return text.ToLower().IndexOf(inner.ToLower(), StringComparison.Ordinal) >= 0;
}
public static bool ContainsIgnoreCase(List<string> list, string target)
{
if (list == null || list.Count == 0) return false;
return list.Any(element => EqualsIgnoreCase(element, target));
}
public static string Trim(string text)
{
return string.IsNullOrEmpty(text) ? string.Empty : text.Trim();
}
public static string TrimAndToLower(string text)
{
return string.IsNullOrEmpty(text) ? string.Empty : text.ToLower().Trim();
}
public static string Remove(string text, int startIndex)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (startIndex >= text.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
return text.Substring(0, startIndex);
}
public static string Guid()
{
return System.Guid.NewGuid().ToString();
}
public static string GetShortGuid()
{
long i = 1;
foreach (var b in System.Guid.NewGuid().ToByteArray())
{
i *= b + 1;
}
return $"{i - DateTime.Now.Ticks:x}";
}
public static string GetShortGuid(bool isUppercase)
{
long i = 1;
foreach (var b in System.Guid.NewGuid().ToByteArray())
{
i *= b + 1;
}
string retval = $"{i - DateTime.Now.Ticks:x}";
return isUppercase ? retval.ToUpper() : retval.ToLower();
}
public static bool EqualsIgnoreCase(string a, string b)
{
if (a == b) return true;
if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(b)) return false;
return a.Equals(b, StringComparison.OrdinalIgnoreCase);
}
public static bool EqualsIgnoreNull(string a, string b)
{
return string.IsNullOrEmpty(a) ? string.IsNullOrEmpty(b) : string.Equals(a, b);
}
public static bool StartsWithIgnoreCase(string text, string startString)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(startString)) return false;
return text.Trim().ToLower().StartsWith(startString.Trim().ToLower()) || string.Equals(text.Trim(), startString.Trim(), StringComparison.OrdinalIgnoreCase);
}
public static bool EndsWithIgnoreCase(string text, string endString)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(endString)) return false;
return text.Trim().ToLower().EndsWith(endString.Trim().ToLower());
}
public static bool StartsWith(string text, string startString)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(startString)) return false;
return text.StartsWith(startString);
}
public static bool EndsWith(string text, string endString)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(endString)) return false;
return text.EndsWith(endString);
}
public static void InsertBefore(string[] insertBeforeArray, StringBuilder contentBuilder, string insertContent)
{
if (contentBuilder == null) return;
foreach (var insertBefore in insertBeforeArray)
{
if (contentBuilder.ToString().IndexOf(insertBefore, StringComparison.Ordinal) != -1)
{
InsertBefore(insertBefore, contentBuilder, insertContent);
return;
}
}
}
private static void InsertBefore(string insertBefore, StringBuilder contentBuilder, string insertContent)
{
if (string.IsNullOrEmpty(insertBefore) || contentBuilder == null) return;
var startIndex = contentBuilder.ToString().IndexOf(insertBefore, StringComparison.Ordinal);
if (startIndex != -1)
{
contentBuilder.Insert(startIndex, insertContent);
}
}
public static void InsertAfter(string[] insertAfterArray, StringBuilder contentBuilder, string insertContent)
{
if (contentBuilder != null)
{
foreach (var insertAfter in insertAfterArray)
{
if (contentBuilder.ToString().IndexOf(insertAfter, StringComparison.Ordinal) != -1)
{
InsertAfter(insertAfter, contentBuilder, insertContent);
return;
}
}
}
}
private static void InsertAfter(string insertAfter, StringBuilder contentBuilder, string insertContent)
{
if (string.IsNullOrEmpty(insertAfter) || contentBuilder == null) return;
var startIndex = contentBuilder.ToString().IndexOf(insertAfter, StringComparison.Ordinal);
if (startIndex == -1) return;
if (startIndex != -1)
{
contentBuilder.Insert(startIndex + insertAfter.Length, insertContent);
}
}
public static string HtmlDecode(string inputString)
{
return HttpUtility.HtmlDecode(inputString);
}
public static string HtmlEncode(string inputString)
{
return HttpUtility.HtmlEncode(inputString);
}
public static string ToXmlContent(string inputString)
{
var contentBuilder = new StringBuilder(inputString);
contentBuilder.Replace("<![CDATA[", string.Empty);
contentBuilder.Replace("]]>", string.Empty);
contentBuilder.Insert(0, "<![CDATA[");
contentBuilder.Append("]]>");
return contentBuilder.ToString();
}
public static string StripTags(string inputString)
{
var retval = RegexUtils.Replace("<script[^>]*>.*?<\\/script>", inputString, string.Empty);
retval = RegexUtils.Replace("<[\\/]?[^>]*>|<[\\S]+", retval, string.Empty);
return retval;
}
public static string StripTags(string inputString, params string[] tagNames)
{
var retval = inputString;
foreach (var tagName in tagNames)
{
retval = RegexUtils.Replace($"<[\\/]?{tagName}[^>]*>|<{tagName}", retval, string.Empty);
}
return retval;
}
public static string StripEntities(string inputString)
{
var retval = RegexUtils.Replace("&[^;]*;", inputString, string.Empty);
return retval;
}
public static string ReplaceIgnoreCase(string original, string pattern, string replacement)
{
if (original == null) return string.Empty;
if (replacement == null) replacement = string.Empty;
var count = 0;
var position0 = 0;
int position1;
var upperString = original.ToUpper();
var upperPattern = pattern.ToUpper();
var inc = (original.Length / pattern.Length) * (replacement.Length - pattern.Length);
var chars = new char[original.Length + Math.Max(0, inc)];
while ((position1 = upperString.IndexOf(upperPattern, position0, StringComparison.Ordinal)) != -1)
{
for (var i = position0; i < position1; ++i) chars[count++] = original[i];
foreach (var t in replacement)
{
chars[count++] = t;
}
position0 = position1 + pattern.Length;
}
if (position0 == 0) return original;
for (var i = position0; i < original.Length; ++i) chars[count++] = original[i];
return new string(chars, 0, count);
}
public static string Replace(string replace, string input, string to)
{
var retval = RegexUtils.Replace(replace, input, to);
if (string.IsNullOrEmpty(replace)) return retval;
if (replace.StartsWith("/") && replace.EndsWith("/"))
{
retval = RegexUtils.Replace(replace.Trim('/'), input, to);
}
else
{
retval = input.Replace(replace, to);
}
return retval;
}
public static void ReplaceHrefOrSrc(StringBuilder builder, string replace, string to)
{
builder.Replace("href=\"" + replace, "href=\"" + to);
builder.Replace("href='" + replace, "href='" + to);
builder.Replace("href=" + replace, "href=" + to);
builder.Replace("href="" + replace, "href="" + to);
builder.Replace("src=\"" + replace, "src=\"" + to);
builder.Replace("src='" + replace, "src='" + to);
builder.Replace("src=" + replace, "src=" + to);
builder.Replace("src="" + replace, "src="" + to);
}
public static string ReplaceFirst(string replace, string input, string to)
{
var pos = input.IndexOf(replace, StringComparison.Ordinal);
if (pos > 0)
{
//取位置前部分+替换字符串+位置(加上查找字符长度)后部分
return input.Substring(0, pos) + to + input.Substring(pos + replace.Length);
}
if (pos == 0)
{
return to + input.Substring(replace.Length);
}
return input;
}
public static string ReplaceStartsWith(string input, string replace, string to)
{
var retval = input;
if (!string.IsNullOrEmpty(input) && !string.IsNullOrEmpty(replace) && input.StartsWith(replace))
{
retval = to + input.Substring(replace.Length);
}
return retval;
}
public static string ReplaceStartsWithIgnoreCase(string input, string replace, string to)
{
var retval = input;
if (!string.IsNullOrEmpty(input) && !string.IsNullOrEmpty(replace) && input.ToLower().StartsWith(replace.ToLower()))
{
retval = to + input.Substring(replace.Length);
}
return retval;
}
public static string ReplaceNewlineToBr(string inputString)
{
if (string.IsNullOrEmpty(inputString)) return string.Empty;
var retVal = new StringBuilder();
inputString = inputString.Trim();
foreach (var t in inputString)
{
switch (t)
{
case '\n':
retVal.Append("<br />");
break;
case '\r':
break;
default:
retVal.Append(t);
break;
}
}
return retVal.ToString();
}
public static string ReplaceNewline(string inputString, string replacement)
{
if (string.IsNullOrEmpty(inputString)) return string.Empty;
var retVal = new StringBuilder();
inputString = inputString.Trim();
foreach (var t in inputString)
{
switch (t)
{
case '\n':
retVal.Append(replacement);
break;
case '\r':
break;
default:
retVal.Append(t);
break;
}
}
return retVal.ToString();
}
public static string MaxLengthText(string inputString, int maxLength, string endString = Constants.Ellipsis)
{
var retval = inputString;
try
{
if (maxLength > 0)
{
var decodedInputString = HttpUtility.HtmlDecode(retval);
retval = decodedInputString;
var totalLength = maxLength * 2;
var length = 0;
var builder = new StringBuilder();
var isOneBytesChar = false;
var lastChar = ' ';
if (!string.IsNullOrEmpty(retval))
{
foreach (var singleChar in retval.ToCharArray())
{
builder.Append(singleChar);
if (IsTwoBytesChar(singleChar))
{
length += 2;
if (length >= totalLength)
{
lastChar = singleChar;
break;
}
}
else
{
length += 1;
if (length == totalLength)
{
isOneBytesChar = true;//已经截取到需要的字数,再多截取一位
}
else if (length > totalLength)
{
lastChar = singleChar;
break;
}
else
{
isOneBytesChar = !isOneBytesChar;
}
}
}
}
if (isOneBytesChar && length > totalLength)
{
builder.Length--;
var theStr = builder.ToString();
retval = builder.ToString();
if (char.IsLetter(lastChar))
{
for (var i = theStr.Length - 1; i > 0; i--)
{
var theChar = theStr[i];
if (!IsTwoBytesChar(theChar) && char.IsLetter(theChar))
{
retval = retval.Substring(0, i - 1);
}
else
{
break;
}
}
//int index = retval.LastIndexOfAny(new char[] { ' ', '\t', '\n', '\v', '\f', '\r', '\x0085' });
//if (index != -1)
//{
// retval = retval.Substring(0, index);
//}
}
}
else
{
retval = builder.ToString();
}
var isCut = decodedInputString != retval;
retval = HttpUtility.HtmlEncode(retval);
if (isCut && endString != null)
{
retval += endString;
}
}
}
catch
{
// ignored
}
return retval;
}
private static Encoding Gb2312 { get; } = Encoding.GetEncoding("gb2312");
private static bool IsTwoBytesChar(char chr)
{
// 使用中文支持编码
return Gb2312.GetByteCount(new[] { chr }) == 2;
}
/// <summary>
/// 得到innerText在content中的数目
/// </summary>
/// <param name="innerText"></param>
/// <param name="content"></param>
/// <returns></returns>
public static int GetCount(string innerText, string content)
{
if (innerText == null || content == null)
{
return 0;
}
var count = 0;
for (var index = content.IndexOf(innerText, StringComparison.Ordinal); index != -1; index = content.IndexOf(innerText, index + innerText.Length, StringComparison.Ordinal))
{
count++;
}
return count;
}
public static int GetStartCount(char startChar, string content)
{
if (content == null)
{
return 0;
}
var count = 0;
foreach (var theChar in content)
{
if (theChar == startChar)
{
count++;
}
else
{
break;
}
}
return count;
}
public static int GetStartCount(string startString, string content)
{
if (content == null)
{
return 0;
}
var count = 0;
while (true)
{
if (content.StartsWith(startString))
{
count++;
content = content.Remove(0, startString.Length);
}
else
{
break;
}
}
return count;
}
public static string GetFirstOfStringCollection(string collection, char separator)
{
if (!string.IsNullOrEmpty(collection))
{
var index = collection.IndexOf(separator);
return index == -1 ? collection : collection.Substring(0, index);
}
return string.Empty;
}
private static int _randomSeq;
public static int GetRandomInt(int minValue, int maxValue)
{
var ro = new Random(unchecked((int)DateTime.Now.Ticks));
var retval = ro.Next(minValue, maxValue);
retval += _randomSeq++;
if (retval >= maxValue)
{
_randomSeq = 0;
retval = minValue;
}
return retval;
}
public static string ValueToUrl(string value)
{
var retval = string.Empty;
if (!string.IsNullOrEmpty(value))
{
//替换url中的换行符,update by sessionliang at 20151211
retval = value.Replace("=", "_equals_").Replace("&", "_and_").Replace("?", "_question_").Replace("'", "_quote_").Replace("+", "_add_").Replace("\r", "").Replace("\n", "");
}
return retval;
}
public static string ValueFromUrl(string value)
{
var retval = string.Empty;
if (!string.IsNullOrEmpty(value))
{
retval = value.Replace("_equals_", "=").Replace("_and_", "&").Replace("_question_", "?").Replace("_quote_", "'").Replace("_add_", "+");
}
return retval;
}
public static string ToJsString(string value)
{
var retval = string.Empty;
if (!string.IsNullOrEmpty(value))
{
retval = value.Replace("'", @"\'").Replace("\r", "\\r").Replace("\n", "\\n");
}
return retval;
}
public static string ParseReplace(string parsedContent, string replace, string to)
{
if (replace.IndexOf(',') != -1)
{
var replaceList = TranslateUtils.StringCollectionToStringList(replace);
var toList = TranslateUtils.StringCollectionToStringList(to);
if (replaceList.Count == toList.Count)
{
for (var i = 0; i < replaceList.Count; i++)
{
parsedContent = parsedContent.Replace(replaceList[i], toList[i]);
}
return parsedContent;
}
if (toList.Count == 1)
{
foreach (var replaceStr in replaceList)
{
parsedContent = parsedContent.Replace(replaceStr, to);
}
return parsedContent;
}
}
string retval;
if (replace.StartsWith("/") && replace.EndsWith("/"))
{
retval = RegexUtils.Replace(replace.Trim('/'), parsedContent, to);
}
else
{
retval = parsedContent.Replace(replace, to);
}
return retval;
}
public static string GetTrueImageHtml(string isDefaultStr)
{
return GetTrueImageHtml(TranslateUtils.ToBool(isDefaultStr));
}
private static string GetTrueImageHtml(bool isDefault)
{
var retval = string.Empty;
if (isDefault)
{
retval = "<img src='../pic/icon/right.gif' border='0'/>";
}
return retval;
}
public static string LowerFirst(string input)
{
if (string.IsNullOrEmpty(input)) return string.Empty;
return input.First().ToString().ToLower() + input.Substring(1);
}
}
}