PHP & MySQL

특정 문자열 사이의 문자열 추출

KJSR71 2015. 5. 27. 13:13

function subString($str, $firstStr, $lastStr, $offset = 0, $full = true) {

$subStr = '';

if(ereg($firstStr, $str) && ereg($lastStr, $str)) {

$startPos = strpos($str, $firstStr, $offset) + strlen($firstStr);

$endPos = strpos($str, $lastStr, $startPos) - $startPos;

$subStr = substr($str, $startPos, $endPos);

if($full) {

$subStr = $firstStr . $subStr . $lastStr;

}

}

return $subStr;

}


function eSubString($str, $firstPattern, $lastPattern, $full = true) {

$sCount = preg_match_all($firstPattern, $str, $matches1, 256);

$eCount = preg_match_all($lastPattern,  $str, $matches2, 256);

$result = array();

if(!$sCount || $sCount > $eCount) {

echo "Count error.(s:$sCount > e:$eCount)";

} else if($sCount > 0) {

for($i = 0; $i < $sCount; $i++) {

array_push($result, subString($str, $matches1[0][$i][0], $matches2[0][$i][0], $matches1[0][$i][1], $full));

}

}

return $result;

}