简体   繁体   中英

How do i get string between two string

i have one string and i need to get text between text

Scenario

SELECT * FROM EMP WHERE EMPID > 0

from above string i need to get

array([0]=>'*',[1]=>'EMP')

function BetweenStr($InputString, $StartStr, $EndStr=0, $StartLoc=0) 
{
    if (($StartLoc = strpos($InputString, $StartStr, $StartLoc)) === false) { return; }
    $StartLoc += strlen($StartStr);
    if (!$EndStr) { $EndStr = $StartStr; }
    if (!$EndLoc = strpos($InputString, $EndStr, $StartLoc)) { return; }
    return substr($InputString, $StartLoc, ($EndLoc-$StartLoc));
}

above function works if i give $InputString, $StartStr and $EndStr but if i did not pass $EndStr it's not work

$hd_qa['SELECT'] = $this->BetweenStr($myQuery,'SELECT','FROM');
**Result => *
$hd_qa['FROM'] = $this->BetweenStr($myQuery,'FROM','WHERE');
**Result => EMP
$hd_qa['WHERE'] = $this->BetweenStr($myQuery,'WHERE','');
** NOT WORKING
$matches = array();
$sql = 'SELECT blah blah blah FROM EMP WHERE EMPID > 0';
preg_match('/SELECT(.+?)FROM(.+?)WHERE(.+)/is', $sql, $matches);
print_r($matches);

echo $matches[1];  // These are what you're looking for
echo $matches[2];

If you want to do it your way, doing like that should do the trick :

function BetweenStr($InputString, $StartStr, $EndStr=0, $StartLoc=0) 
{
    if (($StartLoc = strpos($InputString, $StartStr, $StartLoc)) === false) { return; }
    $StartLoc += strlen($StartStr);
    if (!$EndStr) { $EndLoc = strlen($InputString); }
    if (!$EndLoc = strpos($InputString, $EndStr, $StartLoc)) { return; }
    return substr($InputString, $StartLoc, ($EndLoc-$StartLoc));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM