This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
RegEx pattern to get the YouTube video ID from any YouTube URL
I have stored youtube url in the database.I want to fetch only youtube id from the youtube url.I just want to extract id(6FjfewWAGdE) from below url.
$youtubeVal=http://www.youtube.com/embed/6FjfewWAGdE?feature=player_detailpage
you can do this by
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match&&match[2].length==11){
return match[2];
}
Youtube URLs come in a variety of formats (with the embed/<id> thing or with the watch?v=<id>). Find the URL type(s) you want to understand and build regular expressions to extract them correctly.
Here is a working non-regexp solution in PHP:
function GetYoutubeID($url) {
$temp = parse_url($url);
if(isset($temp['query'])) {
parse_str($temp['query'], $temp2);
if(isset($temp2['v'])) {
return $temp2['v'];
}
}
if(isset($temp['path'])) {
$temp2 = explode("/", $temp['path']);
foreach($temp2 as $value) {
if(strlen($value) == 11 || strlen($value) == 10) {
return $value;
}
}
}
return "no ID?";
}
echo $youtubeID = GetYoutubeID('http://www.youtube.com/embed/6FjfewWAGdE?feature=player_detailpage') . "\n";
echo $youtubeID = GetYoutubeID('https://www.youtube.com/embed/6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('https://youtube.com/embed/6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('http://www.youtube.com/watch?v=6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('http://www.youtube.com/watch?v=6FjfewWAGdE&feature=player_detailpage') . "\n";
echo $youtubeID = GetYoutubeID('www.youtu.be/6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('youtu.be/6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('youtube.com/watch?v=6FjfewWAGdE') . "\n";
echo $youtubeID = GetYoutubeID('https://www.youtube.com/watch?v=6FjfewWAGdE&feature=youtu.be') . "\n";
Replace the whole content of the function with the following to use a more better looking solution (Regular expression):
preg_match('/^(http:\/\/|https:\/\/|.*?)(www.|.*?)(youtube.com|youtu.be)\/(embed\/|watch\?v=|.*?)(.*?)(\?|\&|$)/is', $url, $matches);
if(isset($matches[5])) {
return $matches[5];
}
return "no ID?"
The regular expression solution is also applicable on Javascript:
function GetYoutubeID(url) {
var regExp = /^(http:\/\/|https:\/\/|.*?)(www.|.*?)(youtube.com|youtu.be)\/(embed\/|watch\?v=|.*?)(.*?)(\?|\&|$)/;
var match = url.match(regExp);
if (match){
return match[5];
}
return "no ID?";
}
console.log(GetYoutubeID('http://www.youtube.com/embed/6FjfewWAGdE?feature=player_detailpage'));
console.log(GetYoutubeID('http://www.youtube.com/embed/6FjfewWAGdE?feature=player_detailpage'));
console.log(GetYoutubeID('https://www.youtube.com/embed/6FjfewWAGdE'));
console.log(GetYoutubeID('https://youtube.com/embed/6FjfewWAGdE'));
console.log(GetYoutubeID('http://www.youtube.com/watch?v=6FjfewWAGdE'));
console.log(GetYoutubeID('http://www.youtube.com/watch?v=6FjfewWAGdE&feature=player_detailpage'));
console.log(GetYoutubeID('www.youtu.be/6FjfewWAGdE'));
console.log(GetYoutubeID('youtu.be/6FjfewWAGdE'));
console.log(GetYoutubeID('youtube.com/watch?v=6FjfewWAGdE'));
console.log(GetYoutubeID('https://www.youtube.com/watch?v=6FjfewWAGdE&feature=youtu.be'));
You can always try with
youtubeVal.substring(29, 39);
Related
I need to verify a text to show it in the page of a website. I need to transform all urls links of the the same website(not others urls of other websites) in links. I need to involve all them with the tag <a>. The problem is is the property href, that I need to put the correct url inside it. I am trying to verify all the the text and if I find a url, I need to verify if it contains the substring "http://". If not, I must put it in the href property. I did some attempt, but all their aren't working yet :( . Any idea how can I do this?
My function is below:
$string = "This is a url from my website: http://www.mysite.com.br and I have a article interesting there, the link is http://www.mysite.com.br/articles/what-is-psychology/205967. I need that the secure url link works too https://www.mysite.com.br/articles/what-is-psychology/205967. the following urls must be valid too: www.mysite.com.br and mysite.com.br";
function urlMySite($string){
$verifyUrl = '';
$urls = array("mysite.com.br");
$text = explode(" ", $string);
$alltext = "";
for($i = 0; $i < count($texto); $i++){
foreach ($urls as $value){
$pos = strpos($text[$i], $value);
if (!($pos === false)){
$verifyUrl = " <a href='".$text[$i]."' target='_blank'>".$text[$i]."</a> ";
if (strpos($verifyUrl, 'http://') !== true) {
$verifyUrl = " <a href='http://".$text[$i]."' target='_blank'>".$text[$i]."</a> ";
}
$alltext .= $verifyUrl;
} else {
$alltext .= " ".$text[$i]." ";
}
}
}
return $alltext;
}
You should use PREG_MATCH_ALL to find all occurances of the URL and replace each of the Matches with a clickable Link.
You could use this function:
function augmentText($text){
$pattern = "~(https?|file|ftp)://[a-z0-9./&?:=%-_]*~i";
preg_match_all($pattern, $text, $matches);
if( count($matches[0]) > 0 ){
foreach($matches[0] as $match){
$text = str_replace($match, "<a href='" . $match . "' target='_blank'>" . $match . "</a>", $text);
}
}
return $text;
}
Change the reguylar expression pattern to match only the URL's you want to make clickable.
Good luck
here's my question:
i have the folwing code in my project:
$news = "Article 20.part2";
if(strpos($news,'.part1')) {$news_n = ".part1";}
else if(strpos($news,'.part2')) {$news_n = ".part2";}
else if(strpos($news,'.part3')) {$news_n = ".part3";}
else if(strpos($news,'.part4')) {$news_n = ".part4";}
else if(strpos($news,'.part5')) {$news_n = ".part5";}
echo $news;
echo "Part number:" . $news_n . "- Read more";
What i want is to display the number of the news part, but the problem is that there are articles with +20/+30 parts and i don't want to add
else if(strpos($news,'.part20')) {$news_n = ".part20";}
etc to my code.
Is there any easier way to do this?
Thanks in advance for your help!
you can use PHP preg_match for this
$news = "Article 20.part20";
$matches= array();
if (preg_match("/\.part(\d*)/", $news,$matches)){
$news_n = '.part'. $matches[1];
}
echo $news;
echo "Part number:" . $news_n . "- Read more";
Edit: You can also use $new_n = $matches[0];. $matches[0] gives you the full match and $matches[1] will have the number part.
Edit2: If the .part is the going to be the last item, then you can use much simpler strstr.
$news = "Article 20.part20";
$news_n = strstr($news, ".part");
echo $news;
echo "Part number:" . $news_n . "- Read more";
Maybe something like:
for($i=1;$i<100;$i++)
{
if(strpos($news,'.part'.$i))
$news_n = '.part'.$i;
}
Use a regular expression
$matches=[];
if (preg_match_all('.part\[( ^[0-9]{1,3}$)\]/', $news, $matches)) {
print_r($matches);
}
If the string you are looking for is numbered based as you say in your question you can do:
foreach(range(1, 50) as $i) {
$part = sprintf('.part%d', $i);
if(strpos($news, $part) {
$news_n = sprintf('.%s', $part);
}
}
This question already has answers here:
Using an array as needles in strpos
(16 answers)
Closed 9 years ago.
Im running strpos on a <a> tag to see if it contains either one of two urls.
At the moment im using this bellow - how would i set it to check if - tumblr.com OR google.com were present ?
function find_excluded_url ($url) {
$find = "tumblr.com"; // OR GOOGLE.COM ....
$pos = strpos($url, $find);
if ($pos === false) {
return false;
} else {
return true;
}
}
// SET URL
$url = "<a href='http://tumblr.com/my_post' rel='nofollow'>This site</a>";
// CALL FUNC
$run_url = find_excluded_url($url);
if ($run_url == true) {
echo "URL - " . $url . "<br>";
}
You can't use two needles in strpos. But what you can do, is use it twice, with an or:
function find_excluded_url ($url) {
return (strpos($url, "tumblr.com")!==false) || (strpos($url, "google.com")!==false);
}
For more complicated searches, you might want to look into Regular Expressions. This would work:
$subject = 'blablabgoogle
balblabtumblrasd
blaasdgoogleadsad';
$pattern = '#(?:google\.com|tumblr\.com)#i';
$result = preg_match($pattern, $subject, $subpattern, PREG_OFFSET_CAPTURE);
if($result) echo 'Position: ' . $subpattern[0][1];
The performance of this (if performance is an issue for you) depends on how many search queries you have and how big your haystack is. Regular expressions come with a relatively big overhead, however, they only have to run over the text once. If you use strpos twice, this gets expensive with long strings. If performance is really an issue, you could also write your own strpos that goes character per character. I doubt, however, that this is necessary.
function find_excluded_url ($url, $searchURL) {
$pos = strpos($url, $searchURL);
if ($pos === false) {
return false;
} else {
return true;
}
}
// SET URL
$url = "<a href='http://tumblr.com/my_post' rel='nofollow'>This site</a>";
// CALL FUNC
$run_url = find_excluded_url($url, 'google.com');
if ($run_url == true)
echo "URL - " . $url . "<br>";
$run_url = find_excluded_url($url, 'tumblr.com');
if ($run_url == true)
echo "URL - " . $url . "<br>";
i need to sort some strings and match them with links, this is what i do:
$name_link = $dom->find('div[class=link] strong');
Returns array [0]-[5] containing strings such as NowDownload.eu
$code_link = $dom->find('div[class=link] code');
Returns links that match the names from 0-5, as in link [0] belongs to name [0]
I do not know the order in which they are returned, NowDownload.Eu, could be $code_link[4] or $code_link [3], but the name array will match it in order.
Now, i need $code_link[4] // lets say its NowDownload.Eu to become $link1 every time
so i do this
$i = 0;
while (!empty($code_link[$i]))
SortLinks($name_link, $code_link, $i); // pass all links and names to function, and counter
$i++;
}
function SortLinks($name_link, $code_link, &$i) { // counter is passed by reference since it has to increase after the function
$string = $name_link[$i]->plaintext; // name_link is saved as string
$string = serialize($string); // They are returned in a odd format, not searcheble unless i serialize
if (strpos($string, 'NowDownload.eu')) { // if string contains NowDownload.eu
$link1 = $code_link[$i]->plaintext;
$link1 = html_entity_decode($link1);
return $link1; // return link1
}
elseif (strpos($string, 'Fileswap')) {
$link2 = $code_link[$i]->plaintext;
$link2 = html_entity_decode($link2);
return $link2;
}
elseif (strpos($string, 'Mirrorcreator')) {
$link3 = $code_link[$i]->plaintext;
$link3 = html_entity_decode($link3);
return $link3;
}
elseif (strpos($string, 'Uploaded')) {
$link4 = $code_link[$i]->plaintext;
$link4 = html_entity_decode($link4);
return $link4;
}
elseif (strpos($string, 'Ziddu')) {
$link5 = $code_link[$i]->plaintext;
$link5 = html_entity_decode($link5);
return $link5;
}
elseif (strpos($string, 'ZippyShare')) {
$link6 = $code_link[$i]->plaintext;
$link6 = html_entity_decode($link6);
return $link6;
}
}
echo $link1 . '<br>';
echo $link2 . '<br>';
echo $link3 . '<br>';
echo $link4 . '<br>';
echo $link5 . '<br>';
echo $link6 . '<br>';
die();
I know they it finds the link, i have tested it before, but i wanted to make it a function, and it messed up, is my logic faulty or is there an issue with the way i pass the variables/ararys ?
I don't know why you pass $i as reference since you use it just for reading it. You could return an array contaning the named links and using it like so :
$all_links = SortLinks($name_link,$code_link);
echo $all_links['link1'].'<br/>';
echo $all_links['link2'].'<br/>';
You will have to put your loop inside the function, not outside.
when we add a param to the URL
$redirectURL = $printPageURL . "?mode=1";
it works if $printPageURL is "http://www.somesite.com/print.php", but if $printPageURL is changed in the global file to "http://www.somesite.com/print.php?newUser=1", then the URL becomes badly formed. If the project has 300 files and there are 30 files that append param this way, we need to change all 30 files.
the same if we append using "&mode=1" and $printPageURL changes from "http://www.somesite.com/print.php?new=1" to "http://www.somesite.com/print.php", then the URL is also badly formed.
is there a library in PHP that will automatically handle the "?" and "&", and even checks that existing param exists already and removed that one because it will be replaced by the later one and it is not good if the URL keeps on growing longer?
Update: of the several helpful answers, there seems to be no pre-existing function addParam($url, $newParam) so that we don't need to write it?
Use a combination of parse_url() to explode the URL, parse_str() to explode the query string and http_build_query() to rebuild the querystring. After that you can rebuild the whole url from its original fragments you get from parse_url() and the new query string you built with http_build_query(). As the querystring gets exploded into an associative array (key-value-pairs) modifying the query is as easy as modifying an array in PHP.
EDIT
$query = parse_url('http://www.somesite.com/print.php?mode=1&newUser=1', PHP_URL_QUERY);
// $query = "mode=1&newUser=1"
$params = array();
parse_str($query, $params);
/*
* $params = array(
* 'mode' => '1'
* 'newUser' => '1'
* )
*/
unset($params['newUser']);
$params['mode'] = 2;
$params['done'] = 1;
$query = http_build_query($params);
// $query = "mode=2&done=1"
Use this:
http://hu.php.net/manual/en/function.http-build-query.php
http://www.addedbytes.com/php/querystring-functions/
is a good place to start
EDIT: There's also http://www.php.net/manual/en/class.httpquerystring.php
for example:
$http = new HttpQueryString();
$http->set(array('page' => 1, 'sort' => 'asc'));
$url = "yourfile.php" . $http->toString();
None of these solutions work when the url is of the form:
xyz.co.uk?param1=2&replace_this_param=2
param1 gets dropped all the time
.. which means it never works EVER!
If you look at the code given above:
function addParam($url, $s) {
return adjustParam($url, $s);
}
function delParam($url, $s) {
return adjustParam($url, $s);
}
These functions are IDENTICAL - so how can one add and one delete?!
using WishCow and sgehrig's suggestion, here is a test:
(assuming no anchor for the URL)
<?php
echo "<pre>\n";
function adjustParam($url, $s) {
if (preg_match('/(.*?)\?/', $url, $matches)) $urlWithoutParams = $matches[1];
else $urlWithoutParams = $url;
parse_str(parse_url($url, PHP_URL_QUERY), $params);
if (strpos($s, '=') !== false) {
list($var, $value) = split('=', $s);
$params[$var] = urldecode($value);
return $urlWithoutParams . '?' . http_build_query($params);
} else {
unset($params[$s]);
$newQueryString = http_build_query($params);
if ($newQueryString) return $urlWithoutParams . '?' . $newQueryString;
else return $urlWithoutParams;
}
}
function addParam($url, $s) {
return adjustParam($url, $s);
}
function delParam($url, $s) {
return adjustParam($url, $s);
}
echo "trying add:\n";
echo addParam("http://www.somesite.com/print.php", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?newUser=1&fee=0&", "mode=3"), "\n";
echo addParam("http://www.somesite.com/print.php?mode=1", "mode=3"), "\n";
echo "\n", "now trying delete:\n";
echo delParam("http://www.somesite.com/print.php?mode=1", "mode"), "\n";
echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "mode"), "\n";
echo delParam("http://www.somesite.com/print.php?mode=1&newUser=1", "newUser"), "\n";
?>
and the output is:
trying add:
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?mode=3
http://www.somesite.com/print.php?newUser=1&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?newUser=1&fee=0&mode=3
http://www.somesite.com/print.php?mode=3
now trying delete:
http://www.somesite.com/print.php
http://www.somesite.com/print.php?newUser=1
http://www.somesite.com/print.php?mode=1
You can try this:
function removeParamFromUrl($query, $paramToRemove)
{
$params = parse_url($query);
if(isset($params['query']))
{
$queryParams = array();
parse_str($params['query'], $queryParams);
if(isset($queryParams[$paramToRemove])) unset($queryParams[$paramToRemove]);
$params['query'] = http_build_query($queryParams);
}
$ret = $params['scheme'].'://'.$params['host'].$params['path'];
if(isset($params['query']) && $params['query'] != '' ) $ret .= '?'.$params['query'];
return $ret;
}