Search code examples
phppreg-replacesubstrstrpos

Remove characters from beginning and end string


I want to ouput only MYID from URL. What I did so far:

$url = "https://whatever.expamle.com/display/MYID?out=1234567890?Browser=0?OS=1";
echo substr($url, 0, strpos($url, "?out="));

output: https://whatever.expamle.com/display/MYID

$url = preg_replace('#^https?://whatever.expamle.com/display/#', '', $url);
echo $url;

ouput: MYID?out=1234567890?Browser=0?OS=1

How can I combine this? Thanks.


Solution

  • When the string is always a Uniform Resource Locator (URL), like you present it in your question,

    given the following string:

    $url = "https://whatever.expamle.com/display/MYID?out=1234567890?Browser=0?OS=1";
    

    you can benefit from parsing it first:

    $parts = parse_url($url);
    

    and then making use of the fact that MYID is the last path component:

    $str = preg_replace(
        '~^.*/(?=[^/]*$)~' /* everything but the last path component */,
        '',
        $parts['path']
    );
    
    echo $str, "\n"; # MYID
    

    and then depending on your needs, you can combine with any of the other parts, for example just the last path component with the query string:

    echo "$str?$parts[query]", "\n"; # MYID?out=1234567890?Browser=0?OS=1
    

    Point in case is: If the string already represents structured data, use a dedicated parser to divide it (cut it in smaller pieces). It is then easier to come to the results you're looking for.

    If you're on Linux/Unix, it is even more easy and works without a regular expression as the basename() function returns the paths' last component then (does not work on Windows):

    echo basename(parse_url($url, PHP_URL_PATH)), 
         '?',
         parse_url($url, PHP_URL_QUERY), 
         "\n"
         ;