Ajoy
Ajoy

Reputation: 209

How to get substring of string using starting and ending character in PHP?

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';

Upvotes: 1

Views: 3929

Answers (2)

A.D.
A.D.

Reputation: 2372

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;
}

Upvotes: 0

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

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.

Upvotes: 4

Related Questions