Neeraj Sharma
Neeraj Sharma

Reputation: 346

Fetch personid from text string

I am getting below response from apparel21 api for create person.

HTTP/1.1 201 Created

Cache-Control: private

Location: https://domainName.com.au:8181/retailapi_test/Persons//15668?countryCode=AU

Server: Microsoft-IIS/7.5

X-AspNetMvc-Version: 3.0

X-AspNet-Version: 4.0.30319

X-Powered-By: ASP.NET

Date: Mon, 10 Aug 2015 07:11:38 GMT

Content-Length: 0

Is there any way using which I can only retrieve person id (15668) form above text ?? Can any one please help.

Upvotes: 0

Views: 49

Answers (3)

Professor Abronsius
Professor Abronsius

Reputation: 33823

Another take on the problem, using preg_split and preg_match etc

    $headerlist="
        HTTP/1.1 201 Created

        Cache-Control: private

        Location: https://domainName.com.au:8181/retailapi_test/Persons//15668?countryCode=AU

        Server: Microsoft-IIS/7.5

        X-AspNetMvc-Version: 3.0

        X-AspNet-Version: 4.0.30319

        X-Powered-By: ASP.NET

        Date: Mon, 10 Aug 2015 07:11:38 GMT

        Content-Length: 0";

        $location=false;
        $pieces=array_filter( preg_split( '@\n@', $headerlist ) );

        foreach( $pieces as $pair ) {
            list( $param, $value )=preg_split( '@:\s@',$pair );
            if( strtolower( trim($param) )=='location' ){
                $location=$value;
                break;
            }
        }
        $path=parse_url( $location, PHP_URL_PATH );
        preg_match('@\d+@',$path,$matches);
        $userid=$matches[0];
        echo 'userid:'.$userid;

Upvotes: 0

Harish Lalwani
Harish Lalwani

Reputation: 774

PHP code:

 $hdr_array = http_parse_headers($header);

 $str = $hdr_array['Location'];
 //$str = 'https://domainName.com.au:8181/retailapi_test/Persons//15668?countryCode=AU';

 echo getStringBetween($str , 'Persons//', '?countryCode');

 function getStringBetween($str,$from,$to)
 {
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
    return substr($sub,0,strpos($sub,$to));
 }

using these two answers -

https://stackoverflow.com/a/30084266/2857264

https://stackoverflow.com/a/18680847/2857264

Upvotes: 1

Hassaan
Hassaan

Reputation: 7672

You can use parse_url function to explode URL.

Try

$hdr_array = http_parse_headers($header);

$string = $hdr_array['Location'];
//$string = "https://domainName.com.au:8181/retailapi_test/Persons//15668?countryCode=AU";

$personID = parse_url($string, PHP_URL_PATH);

$personID = str_ireplace('/retailapi_test/Persons//', '', $personID);

echo $personID;

Upvotes: 0

Related Questions