removing part of a string with php

Asked

Viewed 7,434 times

5

I have a variable with the following link:

https://www.youtube.com/embed/z1n34sRv1-A

I need to remove everything that comes before the embed, or need the following id:

z1n34sRv1-A

How can I do this with php?

  • http://answall.com/q/43810/91

  • in this case will not work because it is not a GET parameter it is part of the url.

5 answers

5

You can do it this way:

$url = "https://www.youtube.com/embed/z1n34sRv1-A";
$url = explode("embed/", $url);
$embed = $url[1];

4


You can use the explode to split the string by the bars and take the last position that is the Count of the array:

$url_parts = explode("/", "https://www.youtube.com/embed/z1n34sRv1-A");
echo $url_parts[count($url_parts)-1];
  • perfect, worked 100%

3

uses the

 substr($string,$start,$length);

$string = variable, $start = start of the variable where var cut the string in integer, $length= end of integer variable,

let’s say the url pattern has 25 characters

substr($url,25,strlen($url));

2

Use the strrpos to detect the latter / of the url and, with substr, extract the desired part:

$url = 'https://www.youtube.com/embed/z1n34sRv1-A';

substr($url, strrpos($url, '/') + 1)

The function strrpos finds the last occurrence of / and returns the position. Since we need to take what comes after that, it is necessary to add a +1.

Still using a line, you can ease using array_reverse, to take only the last element of array generated by explode.

 current(array_reverse(explode('/', $url)))

1

$url_parts = explode("/", "https://www.youtube.com/embed/z1n34sRv1-A");

echo end($url_parts);

Browser other questions tagged

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