PHP: Best way to extract text within parenthesis?

后端 未结 8 1477
北海茫月
北海茫月 2020-11-28 06:11

What\'s the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string \"text\" from the string \"ignore everything except this (text)\"

8条回答
  •  醉酒成梦
    2020-11-28 06:37

    This function may be useful.

        public static function getStringBetween($str,$from,$to, $withFromAndTo = false)
        {
           $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
           if ($withFromAndTo)
             return $from . substr($sub,0, strrpos($sub,$to)) . $to;
           else
             return substr($sub,0, strrpos($sub,$to));
        }
        $inputString = "ignore everything except this (text)";
        $outputString = getStringBetween($inputString, '(', ')'));
        echo $outputString; 
        //output will be test
    
        $outputString = getStringBetween($inputString, '(', ')', true));
        echo $outputString; 
        //output will be (test)
    

    strpos() => which is used to find the position of first occurance in a string.

    strrpos() => which is used to find the position of first occurance in a string.

提交回复
热议问题