How to cut a section of a URL from a string with a regular expression?

The good news (especially for me, since regEx is hard) is that it can be done without regex. Using my favourite antique function for extracting substrings by Justin Cook

It seems to me that all you actually need to grab is the url parameter of the final url in the string. To that end I use this function to grab everything after “after=” and before “>”, then simply reassemble into the final link.

There are other approaches including exploding the string and doing some replacements on the results so you get all the links, but you stated you are only looking for the last one

$fullstring = '<https://external.service.com/myusername/api/opportunities>; rel="first",<https://external.service.com/myusername/api/opportunities?before=512a7905-65a3-4845-bb8f-d2363c9e1d95>; rel="prev",<https://external.service.com/myusername/api/opportunities?after=2ab72e09-82d9-4c80-a3bb-4a2fea248695>; rel="next"';

function get_string_between($string, $start, $end){
  $string = ' ' . $string;
  $ini = strpos($string, $start);
  if ($ini == 0) return '';
  $ini += strlen($start);
  $len = strpos($string, $end, $ini) - $ini;
  return substr($string, $ini, $len);
}

$parameter = get_string_between($fullstring, 'after=", ">');

$finalUrl = "https://external.service.com/myusername/api/opportunities?after=".$parameter;

echo $finalUrl;