Do I do something wrong?
I need the youtube code, but it doesn't return the real value.
if(preg_match_all("http:\/\/www\.youtube\.com\/v\/(.*)(.*)", $row->n_texto, $matches){
$code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1][0]."/0.jpg";
}
Edit - ircmaxell Based on the comment, the link structure in the text is:
http:// www.youtube.com/v/plMvAh10HVg%26hl=en%26fs=1%26rel=0
Update
The problem is: my code return a link like this:
http://www.youtube.com/v/plMvAh10HVg%26hl=en%26fs=1%26rel=0
Can I stop it with regexp before appear %26hl=en%26fs=1%26rel=0?
Your regex is not correct. There are more than a few things wrong with it. Now, as far as what you want, try this:
#http://(?:.*)youtube.com/v/([^/\#?]+)#
Now, as for why, let's look at the regex:
http://(?:.*)youtube.com
You're looking for a string that starts with http://, has anything after (www., ww2., or nothing).
/v/
You're looking for /v/ as the start of the URL.
([^/\\#?]+)
You're looking for everything else UP TO another /, a query string (?) or a anchor (#). So that should match the ID you're looking for.
So, it would be
if(preg_match("#http://(?:.*)youtube.com/v/([^/\#?]+)#", $row->n_texto, $matches){
$code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1]."/0.jpg";
}
If you wanted to find all:
if(preg_match_all("#http://(?:.*)youtube.com/v/([^/\#?]+)#", $row->n_texto, $matches){
foreach ($matches[1] as $match) {
$code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$match."/0.jpg";
}
}
the link provided has a space before the 1st w in www.youtube.com, the code you need is :
if(preg_match_all("%http://www\.youtube\.com/v/([\w]+)%i", $row->n_texto , $matches)){
$code = $image_to_thumb .= "http://i1.ytimg.com/vi/".$matches[1][0]."/0.jpg";
}
also, the url you have is encoded, you may want to use urldecode($row->n_texto) before using it.
^http://\w{0,3}.?youtube+\.\w{2,3}/watch\?v=[\w-]{11}
according to http://www.regexlib.com/REDetails.aspx?regexp_id=2569
Related
I have a method of pulling Youtube video data from API links. I use Wordpress and ran into a snag.
In order to pull the thumbnail, views, uploader and video title I need the user to input the 11 character code at the end of watch?v=_______. This is documented with specific instructions for the user, but what if they ignore it and paste the whole url?
// the url 'code' the user should input.
_gXp4hdd2pk
// the wrong way, when the user pastes the whole url.
https://www.youtube.com/watch?v=_gXp4hdd2pk
If the user accidentally pastes the entire URL and not the 11 character code then is there a way I can use PHP to grab either the code or whats at the end of this url (11 characters after 'watch?v='?
Here is my PHP code to pull the data:
// $url is the code at the end of 'watch?v=' that the user inputs
$url = get_post_meta ($post->ID, 'youtube_url', $single = true);
// $code is a variable for placing the $url in a youtube link so I can output it to an API link
$code = 'http://www.youtube.com/watch?v=' . $url;
// $code is called at the end of this oembed code, allowing me to decode json data and pull elements from json to echo in my html
// echoed output returns json file. example: http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v=_gXp4hdd2pk
$json = file_get_contents('http://www.youtube.com/oembed?url='.urlencode($code));
Im looking for something like...
"if user inputs code, use this block of code, else if user inputs whole url use a different block of code, else throw error."
Or... if they use the whole URL can PHP only use a specific section of that url...?
EDIT: Thank you for all the answers! I am new to PHP, so thank you all for your patience. It is difficult for graphic designers to learn PHP, even reading the PHP manual can give us headaches. All of your answers were great and the ones ive tested have worked. Thank you so much :)
Try this,
$code = 'https://www.youtube.com/watch?v=_gXp4hdd2pk';
if (filter_var($code, FILTER_VALIDATE_URL) == TRUE) {
// if `$code` is valid url
$code_arr = explode('?v=', $code);
$query_str = explode('&', $code_arr[1]);
$new_code = $query_str[0];
} else {
// if `$code` is not a valid url like '_gXp4hdd2pk'
$new_code = $code;
}
echo $new_code;
Here's a simple option for you to do, unless you want to use regex like Nisse Engström's Answer.
Using the function parse_url() you could do something like this:
$url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184';
$split = parse_url('https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184');
$params = explode('&', $split['query']);
$video_id = str_replace('v=', '', $params[0]);
now $video_id would return:
_gXp4hdd2pk
from the $url supplied in the above code.
I suggest you read the parse_url() documentation to ensure you understand and grasp it all :-)
Update
for your comment.
You'd use something like this to make sure the parsed value is a valid URL:
// this will check if valid url
if (filter_var($code, FILTER_VALIDATE_URL)) {
// its valid as it returned true
// so run the code
$url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184';
$split = parse_url('https://www.youtube.com/watch?v=_gXp4hdd2pk&list=RD_gXp4hdd2pk#t=184');
$params = explode('&', $split['query']);
$video_id = str_replace('v=', '', $params[0]);
} else {
// they must have posted the video code as the if check returned false.
$video_id = $url;
}
Just try as follows ..
$url =" https://www.youtube.com/watch?v=_gXp4hdd2pk";
$url= explode('?v=', $url);
$endofurl = end($url);
echo $endofurl;
Replace $url variable with input .
I instruct my users to copy and paste the whole youtube url.
Then, I do this:
$video_url = 'https://www.youtube.com/watch?v=_gXp4hdd2pk'; // this is from user input
$parsed_url = parse_url($video_url);
parse_str($parsed_url['query'], $query);
$vidID = isset($query['v']) ? $query['v'] : NULL;
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID; // this is used for the Api
$m = array();
if (preg_match ('#^(https?://www.youtube.com/watch\\?v=)?(.+)$#', $url, $m)) {
$code = $m[2];
} else {
/* No match */
}
The code uses a Regular Expression to match the user input (the subject) against a pattern. The pattern is enclosed in a pair of delimiters (#) of your choice. The rest of the pattern works like this:
^ matches the beginning of the string.
(...) creates a subpattern.
? matches 0 or 1 of the preceeding character or subpattern.
https? matches "http" or "https".
\? matches "?".
(.+) matches 1 or more arbitrary charactes. The . matches any character (except newline). + matches 1 or more of the preceeding character or subpattern.
$ matches the end of the string.
In other words, optionally match an http or https base URL, followed by the video code.
The matches are then written to $m. $m[0] contains the entire string, $m[1] contains the first subpattern (base URL) and $m[2] contains the second subpattern (code).
Looking for how to get the complete string in a URI, after the away?to=
My code:
if (isset($_SERVER[REQUEST_URI])) {
$goto = $_SERVER[REQUEST_URI];
}
if (preg_match("/to=(.+)/", $goto, $goto_url)) {
$link = "<a href='{$goto_url[1]}' target='_blank'>{$goto_url[1]}</a>";
The original link is:
https://domain.com/away?to=http://www.zdf.de/ZDFmediathek#/beitrag/video/2162504/Verschw%C3%B6rung-gegen-die-Freiheit-%281%29
.. but my code is cutting the string after the away?to= to only
http://www.zdf.de/ZDFmediathek
You know the fix for this preg_match function to allow really every character following the away?to= ??
UPDATE:
Found out, that $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING'] is already cutting the original URL. Do you know why and how to prevent that?
try use (.*) to get all after to=
$str = 'away?to=dfkhgkjdshfgkhldsflkgh';
preg_match("/to=(.*)/", $str, $goto_url);
echo $goto_url[1]; //dfkhgkjdshfgkhldsflkgh
Instead of extracting the URL with regex from the request URI you can just get it from the $_GET array:
$link = "<a href='{$_GET['to']}' target='_blank'>{$_GET['to']}</a>";
I am trying to create file links based a variable which has a "prefix" and an extension at the end.
Here's what I have:
$url = "http://www.example.com/mods/" . ereg("^[A-Za-z_\-]+$", $title) . ".php";
Example output of what I wish to have outputted (assuming $title = testing;):
http://www.example.com/mods/testing.php
What it currently outputs:
http://www.example.com/mods/.php
Thanks in advance!
Perhaps this is what you need:
$title = "testing";
if(preg_match("/^[A-Za-z_\-]+$/", $title, $match)){
$url = "http://www.example.com/mods/".$match[0].".php";
}
else{
// Think of something to do here...
}
Now $url is http://www.example.com/mods/testing.php.
Do you want to keep letters and remove all other chars in the URL?
In this case the following should work:
$title = ...
$fixedtitle=preg_replace("/[^A-Za-z_-]/", "", $title);
$url = "http://www.example.com/mods/".$fixedtitle.".php";
the inverted character class will remove everything you do not want.
OK first it's important for you to realize that ereg() is deprecated and will eventually not be available as a command for php, so to prevent an error down the road you should use preg_match instead.
Secondly, both ereg() and preg_match output the status of the match, not the match itself. So
ereg("^[A-Za-z_\-]+$", $title)
will output an integer equal to the length of the string in $title, 0 if there's no match and 1 if there's a match but you didn't pass it another variable to store the matches in.
I'm not sure why it's displaying
http://www.example.com/mods/.php
It should actually be outputting
http://www.example.com/mods/1.php
if everything was working correctly. So there is something going on there, and it's definitely not doing what you want it to. You need to pass another variable to the function that will store all the matches found. If the match is successful (which you can check using the return value of the function) then that variable will be an array of all matches.
Note that with preg_match by default only the first match will be returned. but it will still generate an array (which can be used to get isolated portions of the match) whereas preg_match_all will match multiple things.
See http://www.php.net/manual/en/function.preg-match.php for more details.
Your regex looks more or less correct
So the proper code should look something like:
$title = 'testing'; //making sure that $title is what we think it is
if (preg_match('/^[A-Za-z_\-]+$/',$title,$matches)) {
$url = "http://www.example.com/mods/" . $matches[0] . ".php";
} else {
//match failed, put error code in here
}
for example i've got a string like this:
$html = '
test
test
test
hi
';
and i want to append the absolute url to all hrefs where no abolute domain is given.
$html = '
test
test
test
hi
';
whats the best way to do that? i guess something with RegEx, but my RegEx skills are ** ;)
thanks in advance!
found a good way :
$html = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#", '$1http://mydomain.com/$2$3', $html);
you can use (?!http|mailto) if you have also mailto links in your $html
$domain = 'http://mydomain';
preg_match_all('/href\="(.*?)"/im', $html, $matches);
foreach($matches[1] as $n=>$link) {
if(substr($link, 0, 4) != 'http')
$html = str_replace($matches[1][$n], $domain . $matches[1][$n], $html);
}
The previous answer will cause problems with your first and fourth example because it fails to include a forward slash to separate the page from the page name. Admittedly this can be fixed by simply appending it to the $domain, but if you do that then href="/something.php" will end up with two.
Just to give an alternative Regex solution you could go with something like this...
$pattern = '#'#(?<=href=")(.+?)(?=")#'';
$output = preg_replace_callback($pattern, 'make_absolute', $input);
function make_absolute($link) {
$domain = 'http://domain.com';
if(strpos($link[1], 'http')!==0) {
if(strpos($link[1], '/')!==0) {
return $domain.'/'.$link[1];
} else {
return $domain.$link[1];
}
}
return $link[1];
}
However it is worth noting that with a link such as href="example.html" the link is relative to the current directory neither method shown so far will work correctly for relative links that aren't in the root directory. In order to provide a solution that is though more information would be required about where the information came from.
Okay so i set up this thing so that I can print out page that people came from, and then put dummy tags on certain pages. Some pages have commented out "linkto" tags with text in between them.
My problem is that some of my pages don't have "linkto" text. When I link to this page from there I want it to grab everything between "title" and "/title". How can I change the eregi so that if it turns up empty, it should then grab the title?
Here is what I have so far, I know I just need some kind of if/then but I'm a rank beginner. Thank you in advance for any help:
<?php
$filesource = $_SERVER['HTTP_REFERER'];
$a = fopen($filesource,"r"); //fopen("html_file.html","r");
$string = fread($a,1024);
?>
<?php
if (eregi("<linkto>(.*)</linkto>", $string, $out)) {
$outdata = $out[1];
}
//echo $outdata;
$outdatapart = explode( " " , $outdata);
echo $part[0];
?>
Here you go: if eregi() fails to match, the $outdata assignment will never happen as the if block will not be executed. If it matches, but there's nothing between the tags, $outdata will be assigned an empty string. In both cases, !$outdata will be true, so we can fallback to a second match on the title tag instead.
if(eregi("<linkto>(.*?)</linkto>", $string, $link_match)) {
$outdata = $link_match[1];
}
if(!$outdata && eregi("<title>(.*?)</title>", $string, $title_match)) {
$outdata = $title_match[1];
}
I also changed the (.*) in the match to (.*?). This means, don't be greedy. In the (.*) form, if you had $string set to
<title>Page Title</title> ...
... <iframe><title>A second title tag!</title></iframe>
The regex would match
Page Title</title> ... ... <iframe><title>A second title tag!
Because it tries to match as much as possible, as long as the text is between any and any other !. In the (.*?) form, the match does what you'd expect - it matches
Page Title
And stops as soon as it is able.
...
As an aside, this thing is an interesting scheme, but why do you need it? Pages can link to other pages and pass parameters via the query string:
...
Then somescript.php can access the prevpage parameter via the $_GET['prevpage'] superglobal variable.
Would that solve your problem?
The POSIX regex extension (ereg etc.) will be deprecated as of PHP 5.3.0 and may be gone completely come PHP 6, you're better off using the PCRE functions (preg_match and friends).
The PCRE functions are also faster, binary safe and support more features like non-greedy matching etc.
Just a pointer.
you need if, else.
if(eregi(...))
{
.
.
.
}
else
{
just grab title;
}
perhaps you should have done a quick google search to find this very simple answer.
Just add another if test before you assign the match to $outdata:
if (eregi("<linkto>(.*)</linkto>", $string, $out)) {
if ($out[1] != "") {
$outdata = $out[1];
} else {
// Look in the title.
}
}