Catch string between bars of a PHP variable

Asked

Viewed 268 times

-3

How to get the string inside the first two bars (naacoclqtsafkbsk) with PHP?

I get the url from GET

$url = $_GET['url']

// https://streamango.com/embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4
  • she’ll always be the fourth?

  • Maybe it can change because of different file names... the size may affect I think

2 answers

1

Take a look at the function parse_url() - Interprets a URL and returns its components.

The part you’re interested in is the way, so you can pass the PHP_URL_PATH as the second argument.

$url = "https://streamango.com/embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4";

//var_dump(parse_url($url, PHP_URL_PATH));
//string(58) "/embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4"

$uriSegmentos = explode("/", parse_url($url, PHP_URL_PATH));

echo $uriSegmentos[2];

ideone

1

The value you want is what we call the path segment of the URL (English, segment path). For this, the ideal is to treat the URL as a URL through the function parse_url:

$url = parse_url('https://streamango.com/embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4');

So we took only the part of path of the URL:

$path = trim($url['path'] ?? '/', '/');

With the operator ?? we guarantee that if the URL does not have a path is considered the string "/", as recommended by RFC. With the function trim remove any bar from the beginning or end of path, because for us, at this point, they won’t be useful.

For the string given in the question, the value of $path will be:

embed/naacoclqtsafkbsk/L3j3md0fD3N4g4P34rIz_Legendado_mp4

Thus, we divide the string into bars, generating an array with all the path segments of the URL:

$segments = explode('/', $path);

Which will be the array:

Array
(
    [0] => embed
    [1] => naacoclqtsafkbsk
    [2] => L3j3md0fD3N4g4P34rIz_Legendado_mp4
)

With this, just define which position of the array is interesting to you, since by commenting this doesn’t seem to be very defined yet.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.