1

I am looking for finding middle part of a string using starting tag and ending tag in PHP.

$str = 'Abc/[email protected]/1267890(A-29)';
$agcodedup = substr($str, '(', -1);
$agcode = substr($agcodedup, 1);

final expected value of agcode:

$agcode = 'A-29';
1
  • Need to get string between "(" and ")" . Thank You. Commented Nov 2, 2017 at 8:32

2 Answers 2

4

You can use preg_match

    $str = 'Abc/[email protected]/1267890(A-29)';
    if(  preg_match('/\(([^)]+)\)/', $string, $match ) ) echo $match[1]."\n\n";

Outputs

   A-29

You can check it out here

http://sandbox.onlinephpfunctions.com/code/5b6aa0bf9725b62b87b94edbccc2df1d73450ee4

Basically Regular expression says:

  • start match, matches \( Open Paren literal
  • capture group ( .. )
  • match everything except [^)]+ Close Paren )
  • end match, matches \) Close Paren literal

Oh and if you really have your heart set on substr here you go:

$str = 'Abc/[email protected]/1267890(A-29)';

//this is the location/index of the ( OPEN_PAREN
//strlen 0 based so we add +1 to offset it
$start = strpos( $str,'(') +1;
//this is the location/index of the ) CLOSE_PAREN.
$end = strpos( $str,')');
//we need the length of the substring for the third argument, not its index
$len = ($end-$start);  

echo substr($str, $start, $len );

Ouputs

A-29

And you can test this here

http://sandbox.onlinephpfunctions.com/code/88723be11fc82d88316d32a522030b149a4788aa

If it was me, I would benchmark both methods, and see which is faster.

Sign up to request clarification or add additional context in comments.

Comments

0

May this helps to you.

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 = "Abc/[email protected]/1267890(A-29)";
    $outputString = getStringBetween($inputString, '(', ')');

    echo $outputString; 
    //output will be A-29

    $outputString = getStringBetween($inputString, '(', ')', true);
    echo $outputString; 
    //output will be (A-29)


    return $outputString;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.