Substring before and after in Golang and PHP
20 Jul 2018
function strafter($string, $substring) {
$pos = strpos($string, $substring);
if ($pos === false)
return $string;
else
return(substr($string, $pos+strlen($substring)));
}
function strbefore($string, $substring) {
$pos = strpos($string, $substring);
if ($pos === false)
return $string;
else
return(substr($string, 0, $pos));
}
function strbetween($string, $start, $end)
{
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) {
return '';
}
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
func between(value string, a string, b string) string {
// Get substring between two strings.
posFirst := strings.Index(value, a)
if posFirst == -1 {
return ""
}
posLast := strings.Index(value, b)
if posLast == -1 {
return ""
}
posFirstAdjusted := posFirst + len(a)
if posFirstAdjusted >= posLast {
return ""
}
return value[posFirstAdjusted:posLast]
}
func before(value string, a string) string {
// Get substring before a string.
pos := strings.Index(value, a)
if pos == -1 {
return ""
}
return value[0:pos]
}
func after(value string, a string) string {
// Get substring after a string.
pos := strings.LastIndex(value, a)
if pos == -1 {
return ""
}
adjustedPos := pos + len(a)
if adjustedPos >= len(value) {
return ""
}
return value[adjustedPos:len(value)]
}
Ref:
- http://www.wordinn.com/solution/108/php-getting-part-string-after-and-given-sub-string-or-character
- https://www.dotnetperls.com/between-before-after-go