C/C++
/**
* @description: 获取指定字符串中间的字符
* @example: GetMiddleString("123456","12","56",resultStr);执行后*resultStr="34";
* @param {char} *str - 待截取的总字符串
* @param {char} *leftStr - 左边字符串
* @param {char} *rightStr - 右边字符串
* @param {char} *resultStr - 匹配到的字符串
* @return {int} 1:执行成功 0:没有匹配到字符串
* @remark: 调用者应确保resultStr的buff足够容纳返回的字符串,否则将发生数组越界。
*/
int GetMiddleString(const char *str, const char *leftStr, const char *rightStr, char *resultStr)
{
const int leftStrLen = strlen(leftStr);
const int rightStrLen = strlen(rightStr);
char *leftStrP = strstr(str, leftStr);
char *rightStrP = (leftStrP != NULL) ? (strstr(leftStrP, rightStr)) : (NULL);
int resultStrLen, i;
if (rightStrP==NULL || leftStrLen == 0 || rightStrLen == 0){
*(resultStr++) = '\0';
return 0;
}
resultStrLen = (strlen(leftStrP) - strlen(rightStrP));
for (i = leftStrLen, leftStrP += i; i < resultStrLen; i++){
*(resultStr++) = *(leftStrP++);
}
*(resultStr++) = '\0';
return 1;
}
PHP
/**
* @description: 获取指定字符串中间的字符
* @example: GetMiddleString("123456","12","56");返回"34";
* @param {*} $str - 待截取的总字符串
* @param {*} $leftStr - 左边字符串
* @param {*} $rightStr - 右边字符串
* @return {*} 返回匹配到的字符串
*/
function GetMiddleString($str, $leftStr, $rightStr)
{
$leftStrLen = strlen($leftStr);
$rightStrLen = strlen($rightStr);
$leftStrP = strstr($str, $leftStr);
$rightStrP = ($leftStrP != NULL) ? (strstr($leftStrP, $rightStr)) : (NULL);
if ($rightStrP==NULL || $leftStrLen == 0 || $rightStrLen == 0){
return "";
}
$resultStrLen = (strlen($leftStrP) - strlen($rightStrP));
$resultStr="";
for ($i = $leftStrLen; $i < $resultStrLen; $i++){
$resultStr .= $leftStrP[$i];
}
return $resultStr;
}
JavaScript
/**
* @description: 获取指定字符串中间的字符
* @example: GetMiddleString("123456","12","56");返回"34";
* @param {*} str - 待截取的总字符串
* @param {*} leftStr - 左边字符串
* @param {*} rightStr - 右边字符串
* @return {*} 返回匹配到的字符串
*/
function GetMiddleString(str, leftStr, rightStr)
{
let leftStrLen = leftStr.length;
let rightStrLen = rightStr.length;
let leftStrP = str.indexOf(leftStr);
let rightStrP= str.indexOf(rightStr);
if (leftStrLen == 0 || rightStrLen == 0 || leftStrP == -1 || rightStrP == -1) {
return "";
}
while (rightStrP <= leftStrP && rightStrP != -1) {
rightStrP = str.indexOf(rightStr, (rightStrP + rightStrLen));
}
if (rightStrP == -1) {
return "";
}
return str.substring((leftStrP + leftStrLen), rightStrP);
}