Preg_match url to get id numbers - php

I tried preg_match and explode and everything but doesnt get good solution for getting id numbers in url.
URL-s
$a = strtolower('<iframe src="//LearningApps.org/watch?app=1250652" style="border:0px;width:100%;height:500px" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>');
$b = strtolower('http://LearningApps.org/view1250652');
$c = strtolower('LearningApps.org/view1250652');
$d = strtolower('LearningApps.org/watch?app=1250652');
$e = strtolower('LearningApps.org');
$f = strtolower('http://learningapps.org/339473');
And i tried:
$match = '/[0-9]{7}/';
preg_match($match, $end, $matches);
print_R($matches);
But id lenght can change, so that isnt good solution for me.

As developer of the named service learningapps.org I can provide you with our own PHP function to parse URLs to get the ID:
function getLearningAppID($url){
parse_str( parse_url( $url, PHP_URL_QUERY ), $params );
$ID = null;
$GUID = "";
if(isset($params["v"])) $GUID = $params["v"];
if(isset($params["id"])) $GUID = $params["id"];
if($GUID == ""){
// try AppID
if(preg_match("#learningapps.org/(?:view)?(\d+)#i",$url,$matches)){
$ID = $matches[1];
}else{
if(isset($params["app"])) $ID = $params["app"];
}
}
// now you have either a value in $ID (public app) or $GUID (private app)
...
}
You can also always contact us directly by mail, we are happy to hear about development projects based on learningapps.org :-)

If you are trying to get only the digits, you can use regex.
preg_match("/([0-9]{5,})/", $input_line, $output_array);
Check the code
Or (but case if you have a string with some other numbers the regex below will not work correctly)
preg_replace("/\D/", "", $input_lines);
Check the code

This will work accurately if the iframe style values are same across your entire code:
$c = strtolower('<iframe src="//LearningApps.org/watch?app=1250652" style="border:0px;width:100%;height:500px" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>');
$numbers = intval(preg_replace('/[^0-9]+/', '', substr($c, 0, -100)), 10);
echo $numbers;

Related

remove a part of url using php

I have this url :
http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg
and need to convert to :(remove all url before 1)
1/images/hd-wallpaper-40.jpg
EDIT:
http://localhost/cms/uploads/files/ is dynamic So Maybe : http://localhost/uploads/files/
how do can I convert this url using php?
I don't know the rules/conditions you need but this is a way:
$url = parse_url('http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg');
echo str_replace('/cms/uploads/files/', '', $url['path']);
UPDATE:
If imagesis static:
$url = parse_url('http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg');
preg_match('/[0-99999]\/.*/', $url['path'], $matches);
echo $matches[0];
You can use parse_url function to get whatevers after the host (in this case localhost) and then explode the path, slice an array and implode it back:
$str = "http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg";
$parsed_url = parse_url($str);
echo implode("/", array_slice(explode("/", $parsed_url['path']),4));
a simple solution may be;
$basepath = 'http://localhost/cms/uploads/files/';
$url = 'http://localhost/cms/uploads/files/1/images/hd-wallpaper-40.jpg';
if (strncmp($basepath, $url, strlen($basepath)) == 0 ) {
$result = substr($url, strlen($basepath));
} else {
$result = false;
}
echo $result;
Try this, dynamic content with '/1/' will work perfectly
$str = "http://localhost/cms/uploads/files/1/images/1/hd-wallpaper-40.jpg";
//url as string
$pos = strpos($str,'1'); //position of first '1' in url
$len = strlen($str); //length of url string
$str1 = substr($str,$pos,($len-$pos)); //substring from '1' onwards
There are few drawbacks too. If the '1' occurres before , i mean url = "http://localhost/cms1/uploads/files/1/images, it will give wrong result.
If you use dynamic author id, instead of 1, save author id as a variable and insert in strpos(). The below one will be more accurate and you can use dynamic authorID too.
$str = "http://localhost/cms/uploads/files/1/images/1/hd-wallpaper-40.jpg";
//url as string
$authid = 1; //author id
$searchstring = '/'.$authid.'/'; // create a search string '/1/'
$pos = strpos($str,$searchstring); //position of first '/1/' in url
$len = strlen($str); //length of url string
$str1 = substr($str,$pos+1,($len-$pos)); //substring from '1' onwards

str ireplace PHP parts of url

I have a html doc that has links in it.
Example :
http://mysite1.com/test/whatIwant/Idontwantthis
http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither
I want to replace these with:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
How can I do this? I feel like the only way is to use str_ireplace to get the value that I want and append it to the other link, I just can't seem to remove the part after the value that I want.
I use:
$var= str_ireplace("http://mysite1.com/test/", "http://myothersite.com/", $var);
But then I get the after value still on the link:
http://myothersite.com/whatIwant/Idontwantthis
I tried and now am turning to the community for help.
Thanks
Oh and they are enclosed in the tag with class and other attributes, all I need to change is the URL as explained above.
The links are not in an array they are being edited from a javascript file so they will be in a large variable as text.
$examples =
'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither'
;
Edit: using your updated example, you can split those URLs up by the whitespace between them:
$examples = 'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant3/Idontwantthiseither';
$examples = explode(' ', $examples);
Alternative example array:
$examples = array(
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis',
'http://mysite1.com/test/whatIwant3/Idontwantthiseither'
);
Regex solution:
$pattern = '/^(?:http|https):\/\/.+\/.*\/(.+)\/.*$/Um';
$replace = 'http://myothersite.com/$1';
foreach($examples as $example) {
echo preg_replace($pattern, $replace, $example);
}
Non-regex solution:
foreach($examples as $example) {
// remove the original domain name
$first = str_ireplace('http://mysite1.com/test/', '', $example);
// prepend the new domain name with the first part of the remaining URL
// e.g. strip everything after the first slash
echo 'http://myothersite.com/' . explode('/', $first)[0];
}
Note: using explode(...)[0] is array dereferencing, and is supported in PHP >= 5.4.0. For previous versions of PHP, use a variable to store the array before referencing it:
$bits = explode('/', $first);
echo 'http://myothersite.com/' . $bits[0];
From the manual:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
Example output:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
This function should do the job.
<?php
function EditLink($link)
{
$link = explode("/",$link);
return $link[4];
}
$new_link = "http://myothersite.com/".EditLink("http://mysite1.com/test/whatIwant/Idontwantthis")."";
echo $new_link;
?>
Try this no regex:
$urls = array(
'http://mysite1.com/test/whatIwant3/Idontwantthiseither',
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis'
);
$new_site = "http://myothersite.com/";
foreach ($urls as $url) {
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
echo $var . '<br>';
}
As of PHP 5.3:
$new_urls = array_map(function($url) { // anonymous function
global $new_site;
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
return $var;
}, $urls);
echo implode('<br>', $new_urls);
Sorry by my last answer, you was right, the order was correct.
Try this one with pre_replace, I beleave could solve the problem:
$var = "http://mysite1.com/test/whatIwant/Idontwantthis";
$var = preg_replace("/http\:\/\/mysite1.com\/([^\/]+)\/?.*/", "http://myothersite.com/$1", $var);
echo $var;

Using preg_replace to get id

how to get id url with preg_replace.
this is the link:
http://www.DDDD.com.br/photo/5b87f8eaa7c20f79c3257eb3ec0a35e0/id how do I get the id? in the case would be: 5b87f8eaa7c20f79c3257eb3ec0a35e0
In this case I recommend not to use preg_match (preg_replace would be used to replace something.
Simply use
$array = explode('/',$_SERVER['REQUEST_URI']);
$id = $array[1];
If you must use preg_match:
$array = array();
preg_match('#^/photo/([0-9a-f]{32})/id$#',$_SERVER['REQUEST_URI'],$array);
$id = $array[1];
You can do this easily using strripos to find the last / in the URL.
$url = $_SERVER['REQUEST_URI'];
if (($pos = strripos($url, '/')) !== false) {
$id = substr($url, $pos + 1);
}
else {
trigger_error('You must supply a valid photo ID');
}
If you would like to just extract that id string, you can use:
$id_url = "http://www.DDDD.com.br/photo/5b87f8eaa7c20f79c3257eb3ec0a35e0/id";
$pattern = "/photo\/([a-zA-Z0-9]*)/";
preg_match($pattern, $id_url, $output_array);
echo $output_array[1];
Or, to make the replacement:
$id_url = "http://www.DDDD.com.br/photo/5b87f8eaa7c20f79c3257eb3ec0a35e0/id";
$pattern = "/photo\/([a-zA-Z0-9]*)/";
$replacement = "your replacement";
$replaced_url = preg_replace($pattern, $replacement, $id_url);
echo $replaced_url;
PHP Live Regex - a useful tool for testing your patterns

getting youtube video id the PHP

I am currently writing a webapp in which some pages are heavily reliant on being able to pull the correct youtube video in - and play it. The youtube URLS are supplied by the users and for this reason will generally come in with variants one of them may look like this:
http://www.youtube.com/watch?v=y40ND8kXDlg
while the other may look like this:
http://www.youtube.com/watch/v/y40ND8kXDlg
Currently I am able to pull the ID from the latter using the code below:
function get_youtube_video_id($video_id)
{
// Did we get a URL?
if ( FALSE !== filter_var( $video_id, FILTER_VALIDATE_URL ) )
{
// http://www.youtube.com/v/abcxyz123
if ( FALSE !== strpos( $video_id, '/v/' ) )
{
list( , $video_id ) = explode( '/v/', $video_id );
}
// http://www.youtube.com/watch?v=abcxyz123
else
{
$video_query = parse_url( $video_id, PHP_URL_QUERY );
parse_str( $video_query, $video_params );
$video_id = $video_params['v'];
}
}
return $video_id;
}
How can I deal with URLS that use the ?v version rather than the /v/ version?
Like this:
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = explode("?v=", $link);
$video_id = $video_id[1];
Here is universal solution:
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0&lololo";
$video_id = explode("?v=", $link); // For videos like http://www.youtube.com/watch?v=...
if (empty($video_id[1]))
$video_id = explode("/v/", $link); // For videos like http://www.youtube.com/watch/v/..
$video_id = explode("&", $video_id[1]); // Deleting any other params
$video_id = $video_id[0];
Or just use this regex:
(\?v=|/v/)([-a-zA-Z0-9]+)
<?php
// Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)
// http://youtu.be/dQw4w9WgXcQ
// http://www.youtube.com/embed/dQw4w9WgXcQ
// http://www.youtube.com/watch?v=dQw4w9WgXcQ
// http://www.youtube.com/?v=dQw4w9WgXcQ
// http://www.youtube.com/v/dQw4w9WgXcQ
// http://www.youtube.com/e/dQw4w9WgXcQ
// http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
// http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
// http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
// http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
// It also works on the youtube-nocookie.com URL with the same above options.
// It will also pull the ID from the URL in an embed code (both iframe and object tags)
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
?>
<?php
$your_url='https://www.youtube.com/embed/G_5-SqD2gtA';
function get_youtube_id_from_url($url)
{
if (stristr($url,'youtu.be/'))
{preg_match('/(https:|http:|)(\/\/www\.|\/\/|)(.*?)\/(.{11})/i', $url, $final_ID); return $final_ID[4]; }
else
{#preg_match('/(https:|http:|):(\/\/www\.|\/\/|)(.*?)\/(embed\/|watch.*?v=|)([a-z_A-Z0-9\-]{11})/i', $url, $IDD); return $IDD[5]; }
}
echo get_youtube_id_from_url($your_url)
?>
Try:
function youtubeID($url){
$res = explode("v",$url);
if(isset($res[1])) {
$res1 = explode('&',$res[1]);
if(isset($res1[1])){
$res[1] = $res1[0];
}
$res1 = explode('#',$res[1]);
if(isset($res1[1])){
$res[1] = $res1[0];
}
}
return substr($res[1],1,12);
return false;
}
$url = "http://www.youtube.com/watch/v/y40ND8kXDlg";
echo youtubeID($url1);
Should work for both
Okay, this is a much better answer than my previous:
$link = 'http://www.youtube.com/watch?v=oHg5SJYRHA0&player=normal';
strtok($link, '?');
parse_str(strtok(''));
echo $v;
It's might be good to have this in a function to keep the new variables out of the global scope (unless you want them there, obviously).
This may not be in use still, but there might be other people looking for an answer, so, to get a YouTube ID from a URL.
P.S: This works for all types of URL, I've tested it;
Function getYouTubeID($URL){
$YouTubeCheck = preg_match('![?&]{1}v=([^&]+)!', $URL . '&', $Data);
If($YouTubeCheck){
$VideoID = $Data[1];
}
Return $VideoID;
}
Or just use the preg_match function itself;
If(preg_match('![?&]{1}v=([^&]+)!', $URL . '&', $Data)){
$VideoID = $Data[1];
}
Hope this helps someone :)!
Simplest method I know with YouTube.
function GetYouTubeId($url)
{
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
return $youtube_id;
}
$parts = explode('=', $link);
// $parts[1] will y40ND8kXDlg
This example works only if there's one '=' in the URL. Ever likely to be more?
i just would search for the last "/" or the last "=". After it you find always the video-id.
preg_match("#([\w\d\-]){11}#is", 'http://www.youtube.com/watch?v=y40ND8kXDlg', $matches);
echo $matches[1];
This is best way to get youtube vedio id , Or any field in url , but you must change index (V) from $ID_youtube['v'] to anything you want.
function getID_youtube($url)
{
parse_str(parse_url($url, PHP_URL_QUERY), $ID_youtube);
return $ID_youtube['v'];
}
<?php
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = str_replace('http://www.youtube.com/watch?v=', '', $link);
echo $video_id;
?>
Output:
oHg5SJYRHA0
Source
<?php
$url = "https://www.youtube.com/watch?v=uKW_FPsFiB8&feature=related";
parse_str( parse_url( $url, PHP_URL_QUERY ), $vid );
echo $vid['v'];
?>
Output: uKW_FPsFiB8
This will work for urls like https://www.youtube.com/watch?v=uKW_FPsFiB8&feature=related or https://www.youtube.com/watch?v=vzH8FH1HF3A&feature=relmfu or only https://www.youtube.com/watch?v=uKW_FPsFiB8
All YouTube video ids are 11 characters of length. I wrote Regex based it:
<?php
$url = "https://www.youtube.com/watch?v=gooWdc6kb80";
preg_match('/(?:\/|=)(.{11})(?:$|&|\?)/', $url, $matches);
echo $matches[1];
?>
It can match different YouTube video formats:
// http://youtu.be/dQw4w9WgXcQ
// http://www.youtube.com/embed/dQw4w9WgXcQ
// http://www.youtube.com/watch?v=dQw4w9WgXcQ
// http://www.youtube.com/?v=dQw4w9WgXcQ
// http://www.youtube.com/v/dQw4w9WgXcQ
// http://www.youtube.com/e/dQw4w9WgXcQ
// http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
// http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
// http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
// http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
// https://www.youtube.com/embed/dQw4w9WgXcQ?feature=oembed
// https://www.youtube.com/embed/dQw4w9WgXcQ?start=16&feature=oembed

php - parse friendly url

I have url like this
/cp/foo-bar/another-testing
how to parse it with the pattern
/cp/{0}-{1}/{2}
results will be
0:foo
1:bar
2:another-testing
I need a global solution to parse all kind of url with a pattern like that. I mean using {0}, {1} flag.
if (preg_match('#/cp/([^/]+?)-([^/]+?)/([^/]+)#'), $url, $matches)) {
//look into $matches[1], $matches[2] and $matches[3]
}
Instead of using {0}, {1}, {2}, I offer a new way: using {$s[0]}, {$s[1]}, {$s[2]}:
$your_url = '/cp/foo-bar/another-testing';
$s = explode('/', $your_url);
if(!$s[0])
array_shift($s);
if($temp = array_pop($s))
$s[] = $temp;
//then
$result = "/cp/{$s[0]}-{$s[1]}/{$s[2]}";

Categories