gstr_str.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gstr
  7. import "strings"
  8. // Str returns part of `haystack` string starting from and including
  9. // the first occurrence of `needle` to the end of `haystack`.
  10. // See http://php.net/manual/en/function.strstr.php.
  11. func Str(haystack string, needle string) string {
  12. if needle == "" {
  13. return ""
  14. }
  15. pos := strings.Index(haystack, needle)
  16. if pos == NotFoundIndex {
  17. return ""
  18. }
  19. return haystack[pos+len([]byte(needle))-1:]
  20. }
  21. // StrEx returns part of `haystack` string starting from and excluding
  22. // the first occurrence of `needle` to the end of `haystack`.
  23. func StrEx(haystack string, needle string) string {
  24. if s := Str(haystack, needle); s != "" {
  25. return s[1:]
  26. }
  27. return ""
  28. }
  29. // StrTill returns part of `haystack` string ending to and including
  30. // the first occurrence of `needle` from the start of `haystack`.
  31. func StrTill(haystack string, needle string) string {
  32. pos := strings.Index(haystack, needle)
  33. if pos == NotFoundIndex || pos == 0 {
  34. return ""
  35. }
  36. return haystack[:pos+1]
  37. }
  38. // StrTillEx returns part of `haystack` string ending to and excluding
  39. // the first occurrence of `needle` from the start of `haystack`.
  40. func StrTillEx(haystack string, needle string) string {
  41. pos := strings.Index(haystack, needle)
  42. if pos == NotFoundIndex || pos == 0 {
  43. return ""
  44. }
  45. return haystack[:pos]
  46. }