PHP: str_replace within a word/phrase - php

I am trying to set up a small script that can play youtube videos but thats kinda besides the point.
I have $ytlink which equals www.youtube.com/watch?v=3WAOxKOmR90
But I want to make it become www.youtube.com/embed/3WAOxKOmR90
Currently I have tried
$result = str_replace('https://youtube.com/watch?v=', "https://youtube.com/watch?v=", $ytlink);
But this returns it as standard
I have also tried
preg_replace('/https://youtube.com/watch?v=/, '/https://youtube.com/embed/', $ytlink);
but both of these dont work.

Instead of using ugly regexes, I recommend using parse_url() with parse_str(). This allows you to be flexible in the event that you want to change something or if Youtube decides to change their URL slightly.
$url = 'https://www.youtube.com/watch?v=3WAOxKOmR90';
// Parse the URL into parts
$parsed_url = parse_url($url);
// Get the whole query string
$query = $parsed_url['query'];
// Parse the query string into parts
parse_str($query, $params);
// Get the parameter you want
$v = $params['v'];
// Now re-build the URL how you want
echo $parsed_url['scheme'].'://'.$parsed_url['host'].'/embed/'.$v;
// Outputs: https://www.youtube.com/embed/3WAOxKOmR90

This works:
$ytlink = 'www.youtube.com/watch?v=3WAOxKOmR90';
$result = str_replace('watch?v=', 'embed/', $ytlink);
echo $result;

$url = 'www.youtube.com/watch?v=3WAOxKOmR90';
echo preg_replace('/.*?v=(\w+)/i', 'www.youtube.com/embed/$1', $url);

Related

changing get variable using parse_url not working in php

I've looked at every post on SO that remotely pertains to this and I just can't figure this out. This code is taken directly from another SO post and was marked as the correct working answer:
$query = $_GET;
// replace parameter(s)
$query['d'] = 'new_value';
// rebuild url
$query_result = http_build_query($query);
// new link
Link
Again, taken straight from another post. When I try this code, i change the $_GET to the actual URL that i want to alter. When the code gets to the $query['d'] part, it tells me I get an illegal string offset and the error is the index that's specified. So then I parse the URL, and then do parse_str($query, $output) which in turn allows me to do $output['d'] and THEN I can set a new value to that variable. If I echo it out, it's fine.
But then I get to the http_build_query line, and it tells me that it's expecting an array or object and I can't build the new URL. Here is my code:
$link = parse_url('https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=coding+tutorial', PHP_URL_QUERY);
parse_str($link, $output);
$output['oq'] = 'new value';
$query_result = http_build_query($link);
echo $query_result;
This code yields that the http_build_query function wants an array or object...i guess i'm not giving it that in some way? What do I need to do to get this to work?
If you want to rebuild the full URL after modifying the query parameters, you could do this:
$url = 'https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=coding+tutorial';
$link = parse_url($url, PHP_URL_QUERY);
parse_str($link, $output);
$output['oq'] = 'new value';
echo substr($url, 0, strpos($url, '?') + 1) . http_build_query($output);
Output:
https://www.google.com/search?source=hp&ei=85GhW6CNHoSqsgXnzoD4Ag&q=coding+tutorial&btnK=Google+Search&oq=new+value

PHP: How can i read the second part of URL

How can I take out the part of the url after the view name
Example:
The URL:
http://localhost/winner/container.php?fun=page&view=eims
Extraction
eims
This is called a GET parameter. You can get it by using
<?php
$view = $_GET['view'];
If this is for a URL which is not part of your website (e.g. Not your domain), but you wish to parse it. Something like this will work
$url = "http://example.com/index.php?foo=bar&acme=baz&view=asdf";
$params = explode('?', $url)[1]; // This gets the text AFTER the ? Note: If using PHP 5.3 or less, this may not work. You would then need to split it into two lines with the [1] happening on $params.
$pairs = explode('&', $params);
foreach($pairs as $p => $pair) {
list($keys[$p], $values[$p]) = explode('=', $pair);
$splits[$keys[$p]] = $values[$p];
}
echo $splits['view'];
<?php echo $_GET['view']; ?> //eims
If that's current URL, the simple and rock solid approach is to use the filter functions:
filter_input(INPUT_GET, 'view')
Otherwise, you can use parse_url() with PHP_URL_QUERY as second argument. The resulting string can be split with e.g. parse_str().
Are sure you are writing this "echo $_GET['view'];" in the container.php file?
Maybe write why do you need that "view".

Cut some word from php available?

Cut some word from php available ?
First access to page for example
www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success
From my php code, i will get $curreny_link_redirect = test.php?ABD_07,_oU_876.00/8999&message=success
And i want to get $curreny_link_redirect_new = test.php?ABD_07,_oU_876.00/8999
( Cut &message=success )
How can i do ?
<?PHP
$current_link = "$_SERVER[REQUEST_URI]";
$curreny_link_redirect = substr($current_link,1);
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
echo $curreny_link_redirect_new;
?>
Your str_replace call is inverse of what it should be. What you want to replace should be the first parameter, not the second.
//Wrong
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
//Right
$curreny_link_redirect_new = str_replace('&message=success','', $curreny_link_redirect);
While simple way to do this is to use regex (or even static with str_replace()), I recommend to use built-in functions for url handling. This may be useful when working with complex parameters or multiple parameters:
$data = 'www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success';
$url = parse_url($data);
parse_str($url['query'], $url['query']);
//now, do something with parameters:
unset($url['query']['message']);
$url['query'] = http_build_query($url['query']);
$url = http_build_url($url);
-please, note, that http_build_url() is a PECL function (pecl_http to be precise). The way above may look more complex, but it has benefits - first, as I've already mentioned, this will be easy to modify for working with complex parameters or multiple parameters. Second, it will produce valid url - i.e. encode such things as slashes, spaces, e t.c. - in result. Thus, result will always be correct url.
Do like this
<?php
$str = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $str = array_shift(explode('&',$str));
Try this:
$current_link_path = substr($_SERVER['PHP_SELF'], 1);
$params = $_GET;
if ($params['message'] == 'success') {
unset($params['message']);
}
$current_link_redirect = $current_link_path . '?' . http_build_query($params);
Maybe not an answer, but a disclaimer for future visitors:
1) I would strongly recommend the function: http://pl1.php.net/parse_url.
And in that case:
$current_link = "$_SERVER[REQUEST_URI]";
$arguments = explode('&', parse_url($current_link, PHP_URL_QUERY));
print_r($arguments);
2) To build new url, use http://pl1.php.net/manual/en/function.http-build-url.php. This is the best, future modifications ready solution I think.
In that case this solution is a little overkill, but these functions are really great, and worth to introduce here.
Best regards

Extracting a string from a string where the string is variable

I want to get the individual ID from a youtube link so that I can use it later on, to pull other information such as its thumbnail image and insert it into the embedded iframe.
I notice there that all, I hope, of the urls on youtube start http://www.youtube.com/watch?v= Unique video ID and then depending on a few things can end something like &list=RD02M5u5zXVmoHM. But the unique id always has a & after it and the watch?v= before. Is this the best way to do it? Have a written this correctly?
$link=$_POST['link'];
$link_id=str_replace('http://www.youtube.com/watch?v=', '', $link);
$link_id=strstr($link_id, '&', true);
This comes from form data. Is there anything other variables from youtube URLs I may encounter?
What you want to do is use: http://php.net/pase_url and http://php.net/parse_str like this:
<?php
$info = parse_url("https://www.youtube.com/watch?v=DA57FOJSdM8");
parse_str($info["query"], $query);
print_r($query);
// Outputs: Array ( [v] => DA57FOJSdM8 )
A combination of parse_url() and parse_str() would be a simpler way where PHP handles the dirty work for you. Example:
$video_id = false;
$url_parts = parse_url($link);
$query_params = array();
if (isset($url_parts['query']))
{
parse_str($url_parts['query'], $query_params);
}
if (isset($query_params['v']))
{
$video_id = $query_params['v'];
}
And now $video_id contains the ID you need.

Grab the video ID only from youtube's URLs

How can I grab the video ID only from the youtube's URLs?
For instance,
http://www.youtube.com/watch?v=aPm3QVKlBJg
sometime the URLs contain other information after the 'v' like
http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index
but I don't want the other info, just video ID.
I only can think of using explode,
$url = "http://www.youtube.com/watch?v=aPm3QVKlBJg";
$pieces = explode("v=", $url);
but how to clean up the URLs like this?
http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index
You should never use regular expressions when the same thing can be accomplished through purpose-built functions.
You can use parse_url to break the URL up into its segments, and parse_str to break the query string portion into a key/value array:
$url = 'http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index'
// break the URL into its components
$parts = parse_url($url);
// $parts['query'] contains the query string: 'v=Z29MkJdMKqs&feature=grec_index'
// parse variables into key=>value array
$query = array();
parse_str($parts['query'], $query);
echo $query['v']; // Z29MkJdMKqs
echo $query['feature'] // grec_index
The alternate form of parse_str extracts variables into the current scope. You could build this into a function to find and return the v parameter:
// Returns null if video id doesn't exist in URL
function get_video_id($url) {
$parts = parse_url($url);
// Make sure $url had a query string
if (!array_key_exists('query', $parts))
return null;
parse_str($parts['query']);
// Return the 'v' parameter if it existed
return isset($v) ? $v : null;
}

Categories