Using if/else operator in php code - php

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);
}
}

Related

Show error when url isnt allowed list?

if $text isnt allowed list print error. Dont know how do do it
$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');
$text = 'this is my url www.abcd.com/index.php?page=home';
try like this
$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');
if ( !in_array('your-domain-name', $allowedDomains) {
echo 'show your error here';
} else {
echo 'do what ever you want here';
}
Here's another way of doing it: create a regex using the list of domains, and then use that to test your text strings.
$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');
# concatenate the allowed domains with | and surround with brackets so the regex will
# match any of the array items
# i.e. $regex is (www.test1.com|www.test2.co.uk|test3.com)
$regex = "(" . implode("|", $allowedDomains) . ")";
# a couple of test strings
$texts = array('this is my url www.abcd.com/index.php?page=home',
'my home page is www.test3.com');
foreach ($texts as $t) {
if (preg_match("/$regex/", $t)) {
echo "Found a match! $t\n";
}
else {
echo "No match found: $t\n";
}
}
Output:
No match found: this is my url www.abcd.com/index.php?page=home
Found a match! my home page is www.test3.com
I've written a function for you that'll allow you to add / remove domain names and / or domain extensions as you please, taking into account that not everyone types "http(s)" and / or "www" into their domain searches and also the unpredictability of what kind of information might be behind the domain or not:
<?php
function testDomain($domain){
//Set domain names
$arrDomainNames = array("test1","test2","test3");
//Set domain extensions like .com .co .info
//Do NOT add .co.uk! .uk is taken care of in the regex
$arrDomainExt = array("com","co");
$cntDomainNames = count($arrDomainNames);
$cntDomainExt = count($arrDomainExt);
$i = 0;
$y = 0;
$DomNames = "";
$DomExt = "";
foreach($arrDomainNames as $value){
if($i == $cntDomainNames - 1){
$DomNames .= $value;
} else {
$DomNames .= $value ."|";
}
$i++;
}
unset($value);
foreach($arrDomainExt as $value){
if($y == $cntDomainExt - 1){
$DomExt .= $value;
} else {
$DomExt .= $value ."|";
}
$y++;
}
unset($value);
$pattern = "/((((http|ftp|https)+(:)+(\/{2})))?+(www\.)?(((". $DomNames .")+\.)+(". $DomExt .")+(\.uk)?(:[0-9]+)?((\/([~0-9a-zA-Z\#\+\%#\.\/_-]+))?(\?[0-9a-zA-Z\+\%#\/&\[\];=_-]+)?)?))\b/imu";
if(preg_match($pattern, $domain)){
echo "Domain match!<br />";
} else {
echo "Domain not match!<br />";
}
}
testDomain("www.test1.com"); //match
testDomain("test1.com"); //match
testDomain("http://www.test1.co.uk"); //match
testDomain("test1.com/info.php?who=you"); //match
testDomain("www.google.com"); //no match
?>
How to make it working with
$arrDomainNames = array("test1.com","test2.org","test3.co.uk","test3.net");
without
$arrDomainExt = array("com","co");

Sorting strings, in a function, is my logic faulty or?

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.

How to fetch youtube id from the youtube url? [duplicate]

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);

preg_match find multiple partial appearances of a word in a string

Any regex gurus around here? its driving me crazy.
Say I have this string:
"bookstore books Booking"
I want to count the number "books" appears in this and return the number.
Currently I have this which is not working:
$string = "bookstore books Booking";
if (preg_match_all('/\b[A-Z]+books\b/', $string, $matches)) {
echo count($matches[0]) . " matches found";
} else {
echo "match NOT found";
}
On top of this the "books" inside the preg_match_all should become a $var
Anyone an idea how to count correctly?
It's actually much simpler, you can use preg_match_all() like this:
$string = "bookstore books Booking";
$var = "books";
if (preg_match_all('/' . $var . '/', $string, $matches)) {
echo count($matches[0]) . " matches found";
} else {
echo "match NOT found";
}
Or use the function that was made for this purpose, substr_count():
$string = "bookstore books Booking";
$var = "books";
if ($count = substr_count($string, $var)) {
echo $count . " matches found";
} else {
echo "match NOT found";
}

Regular Expression (preg_match_all)

I have a private website where I share videos (and some other stuff).
What I have achieved is that with preg_match_all() it automatically finds the link and it paste the video with the HTML code to my website.
Here an example:
<?php
$matchwith = "http://videosite.com/id1 http://videosite.com/id2 http://videosite.com/id3";
preg_match_all('/videosite\.com\/(\w+)/i', $matchwith, $matches);
foreach($matches[1] as $value)
{
print 'Hyperlink';
}
?>
This works. I know this could may could be done easier, but it has to be this way.
But I do not know how this with a two part movie. Here an example:
$matchWith = "http://videosite.com/id1_movie1 http://videosite.com/id2_movie1"
"http://videosite.com/id3_movie2 http://videosite.com/id4_movie2";
Everything after http://videosite.com/(...) is unique.
What I want is if you write Part 1 and Part 2 (or whatever) before the link, that it automatically detects it as Part 1 and Part 2 of this video.
$matchwith could contain different movies.
So I believe this is what you need:
<?php
$matchWith = "Movie 1 http://videosite.com/id1" . PHP_EOL .
"Movie 1 http://videosite.com/id2" . PHP_EOL .
"Movie 2 http://videosite.com/id3";
$arrLinks = array();
preg_match_all('%(.*)\shttp://videosite\.com/(\w+)\r{0,1}%', $matchWith, $result, PREG_SET_ORDER);
for ($matchi = 0; $matchi < count($result); $matchi++) {
$arrLinks[$result[$matchi][1]][] = $result[$matchi][2];
}
foreach ($arrLinks as $movieName => $arrMovieIds) {
print '<div>' . $movieName . '</div>';
foreach ($arrMovieIds as $movieId) {
print 'Hyperlink<br/>';
}
}
?>
$matchwith = "Part 1 http://videosite.com/id1-1 Part2 http://videosite.com/id1-2";
preg_match_all('/videosite\.com\/(\w+-\d+)/i', $matchwith, $matches);
foreach($matches[1] as $value)
{
print 'Hyperlink';
}

Categories