I have few url in my database, it goes like:
id url
1 http://test.com/embed-990.html
2. http://test2.com/embed-011.html
3. http://test3.com/embed-022.html
How I could make a simple php code if one of url doesn't exist in database, just to load another? I need to check these url by domain as well.
For example something like this:
if($data['url'] == "test.com") {
echo "my embed code number 1";
} elseif($data['url'] == "test2.com") {
echo "my another embed code";
}
You can parse the URL to get the host then compare it.
$dataurl = array('http://test.com/embed-990.html',
'http://test2.com/embed-011.html',
'http://test3.com/embed-022.html');
foreach($dataurl as $url) {
switch(parse_url($url, PHP_URL_HOST)) {
case 'test.com':
echo 'test domain';
break;
case 'test2.com':
echo 'test domain 2';
break;
default:
echo 'unknown';
break;
}
echo $url . PHP_EOL;
}
Demo: https://3v4l.org/nmukK
For the question Something like SQL “LIKE” you could use a regex in preg_match.
You can use substr_count
if (substr_count($data['url'], 'test.com') > 0) {
echo "my embed code number 1";
}
else if (substr_count($data['url'], 'test2.com') > 0) {
echo "my embed code number 2";
}
or strpos
if (strpos($data['url'],'test.com') !== false) {
echo "my embed code number 1";
}
else if (strpos($data['url'],'test2.com') !== false) {
echo "my embed code number 2";
}
or preg_match
if(preg_match('/test.com/',$data['url']))
{
echo "my embed code number 1";
}
else if(preg_match('/test2.com/',$data['url']))
{
echo "my embed code number 2";
}
You can use Regx
$domains = ['test.com', 'test1.com', 'test20.com'];
foreach( $domains as $domain ){
if(preg_match('/test([0-9]*)\.com/', $domain, $match)){
echo "my embed code number {$match[1]}\n";
}
}
Outputs:
my embed code number
my embed code number 1
my embed code number 20
you can test it here
http://sandbox.onlinephpfunctions.com/code/1d4ed1d7505a43b5a06b5ef6ef83468b20b47799
For the regx
test matches test literally
([0-9]*) - capture group, matches 0-9 none or more times
\. matches . literally
com matches com literally
One thing to note is that placing the * outside the capture group ([0-9])* will match and pass the if, but will not capture anything within the capture group. This makes sense, but its important to note because you'll get this message:
Notice: Undefined offset: 1 in [...][...] on line 6
for test.com.
If you want to match the number in embed- You can use one of these
'/test\.com\/embed-([0-9]{3})\.html/'
'/\/embed-([0-9]{3})\.html/'
'/\/embed-([0-9]{3})\./'
Depending how specific you want to be. You can play around with different Regx on this page.
https://regex101.com/r/snuqRc/1
Regular expressions are very powerful, they are meant for pattern matching, which is what you need.
Cheers.
Related
I'm writing a code what compares a links from imdb and tmdb.
The code matches link to imdb and then transforms it for the tmdb link, if was inserted.
The links look like:
https://www.imdb.com/title/tt0848228
https://www.themoviedb.org/movie/24428
I want to ask if these regexs are correct for movies links.
For ex.
$imdb_url = https://www.imdb.com/title/tt0848228
if (strpos($imdb_url, 'themoviedb.org') == true) {
preg_match_all('/\\d*-/', $imdb_url, $tmdb_id);
$tmdb_id = $tmdb_id[0];
$tmdb_id = str_replace('-', '', $tmdb_id);
$tmdb_id = $tmdb_id[0];
$request_url = amy_movie_provider_build_query_url('tmdb', $tmdb_id, $api_key);
$the_data = wp_remote_get($request_url, array(
'timeout' => $timeout,
));
if (!is_wp_error($the_data) && !empty($the_data)) {
$movie_data = json_decode($the_data['body'], true);
$result = amy_movie_add_tmdb_movie_data($movie_data);
echo $result;
exit;
} else {
$result = esc_html__('Provider TMDB being error!', 'amy-movie-extend');
echo $result;
exit;
}
exit;
}
And else for imdb link:
else if (strpos($imdb_url, 'www.imdb.com') == true) {
preg_match_all('/tt\\d{7}/', $imdb_url, $imdb_id);
$imdb_id = $imdb_id[0];
$imdb_id = $imdb_id[0];
}
I think it's not working because something may be wrong with not existing /movie prefix in the link, but I tried changing that and it still catches error 404.
Why not combining the domain part with the rest of the URI? Why once omitting the subdomain and once making it mandatory?
$sURI= 'whatever';
if( preg_match( '#imdb\\.com/title/tt(\\d{7})#i', $sURI, $aMatch ) ) {
echo 'IMDb, movie #'. $aMatch[1];
} else
if( preg_match( '#themoviedb.org/movie/(\\d+)($|-)#i', $sURI, $aMatch ) ) {
echo 'TMDb, movie #'. $aMatch[1];
} else {
echo 'Unrecognized';
}
This way it doesn't matter if the IMDb URI comes with www. or not. Since the movie IDs have a fixed length we don't even need to expect/care a slash following. Your mistake was expecting a slash without any need.
Same for TMDb, which either ends right away (but we want to get all digits to the end, not just the first) or is followed by a dash. i is for really distorted URIs for whichever reason. Your mistake was to expect a dash and to make digits entirely optional (when at least one should be needed, as in https://www.themoviedb.org/movie/9)
Side note: Using \\d in a PHP string for a regular expression is the correct way, as you first have to deal with the string context - there an effective backslash has to be escaped by the backslash itself. And only after that the scope of the regular expression is encountered. \d only also works because unknown string escapings are silently ignored.
I'm having php script that deals with thousands of queries starting just like (i.e. http://localhost:1234/browse.php?cat=2) so I don't want to write thousands of URLs in an array to deal with if and else condition such as below,
Please guide me how can i make it possible to use "?" sign in my url to distinguish between what command to process if url contains "?" sign.
I used "/browse.php?*" in code as shown in below example but it's not working for me still...Please guide because I'm new in php and search and lot regarding this answer but unable to find a single authentic answer for it, thanks
if(in_array($_SERVER['REQUEST_URI'],array('/browse.php','/browse.php?*')))
{
echo "<Something Like this 1>";
}
elseif ($url == "")
{
echo "<Something Like this 2>";
};
in_array would only check for a full match here and is not appropriate for what you are trying to do. PHP has many String Functions you should look at.
if (strpos($_SERVER['REQUEST_URI'], '?') !== false) {
//URL has '?' mark
}
else{
//URL has no '?' mark
}
I believe you are only concerned with the cat URL search parameter? If so, you can access this parameter in your browse.php script using the $_GET array:
<?php
if (array_key_exists('cat', $_GET)) {
echo "cat parameter: {$_GET['cat']}"; // display ?cat=value
} else {
echo 'No cat URL parameter'; // ?cat was not in the URL
}
?>
http://localhost:1234/browse.php -> No cat URL parameter
http://localhost:1234/browse.php?cat=57890 -> cat parameter: 57890
I've got a blog, I want to display ADS or special text on the MAIN page but not on any other page with the URI /?paged=[number]. I've tried the standard regex /^[0-9].$/ but it fails to match.
I'm not sure what I've done wrong or how to go about doing this
if (substr_count($_SERVER[REQUEST_URI], "/") > 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=1") == 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=2") == 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=3") == 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=4") == 0 AND
substr_count($_SERVER[REQUEST_URI], "/?paged=5") == 0) {
echo "display special text, banners, and other stuff";
}
This is how I'm doing it currently, but I don't want to do thousands of these...
Can you not just check for the presence of paged in the GET array?
if(!isset($_GET['paged'])) {
// You know this is the main page.
}
Try this:
if (preg_match('#paged=\d+#', $_SERVER[REQUEST_URI]) {
echo "display special text, banners, and other stuff";
}
Regex: /^[0-9].$/ would be correct for "3k" string. Analize this patterns
/page=(\d+)/
/page=([1-5])/
/^\/\?page=([1-5])$/
/page=(?<page>[1-5])/
Why not using the regexp in the GET parameter ?
<?php
$regexp = "/^(\d+)+$";
if (preg_match($regexp, $_GET['paged'])) {
#...your code
} else {
#...your code
}
Or (if you want to use the entire string) try this:
<?php
$regexp = "/^(\/\?paged)+=(\d+)+$/";
I am trying to validate if a domain does have GET parameters with preg_match and and a REGEX, which i require it to have for my purposes.
What I have got working is validating a domain without GET parameters like so:
if (preg_match("/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}$/", 'domain.com')) {
echo 'true';
} else {
echo 'false';
}
I get true for this test.
So far so good. What I am having trouble with is adding in the GET parameters, Amongst a number of REGEX's I have tried with still no luck is the following:
if (preg_match("/^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}([/?].*)?$/", 'domain.com?test=test')) {
echo 'true';
} else {
echo 'false';
}
Here i get false returned and hence am not able to validate a domain with GET parameters which are required.
Any assistance will be much appreciated ^^
Regards
This code is not tested, but I think it should work:
$pattern = "([a-z0-9-.]*)\.([a-z]{2,3})"; //Host
$pattern .= "(\?[a-z+&\$_.-][a-z0-9;:#&%=+\/\$_.-]*)?"; //Get requests
if (preg_match($pattern, 'domain.com?test=test')) {
echo 'true';
} else {
echo 'false';
}
What is the advantage of using a REGEX?
Why not just
<?php
$xGETS = count($_GET);
if(!$xGETS)
{
echo 'false';
} else {
echo 'true';
}
// PHP 5.2+
$xGETS = filter_var('http://domain.com?test=test', FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED);
if(!$xGETS)
{
echo 'false';
} else {
echo 'true';
}
Your first regular expression will reject some valid domain names (e.g. from the museum and travel TLDs and domain names that include upper case letters) and will recognize some invalid domain names (e.g. where a label or the whole domain name is too long).
If this is fine with you, you might just as well search for the first question mark and treat the prefix as domain name and the suffix as "GET parameters" (actually called query string).
If this is not fine with you, a simple regular expression will not suffice to validate domain names, because of the length constraints of domain names and labels.
I wrote a php search script on my site for checking to see if a package exists in a text file or not (I used file_get_contents.) It takes what the user entered and combines it with the string 'BUILD: ' Below is an example of the file and I'll explain in the paragraph following it:
BUILD: packageA
URL: www.package-a.com
BUILD: packageB
URL: www.package-b.com
BUILD: packageC
URL: www.package-c.com
So if a user were to search "packageB", it would be combined with "BUILD: " making the variable I'm testing with have the value: "BUILD: packageB". I have a conditional saying if that string exists or not; everything's working good on that end.
My question/problem is how can I list the URL: line beneath it with an echo? I've been testing some ideas with strlen() and I can't seem to get it and the text file has different strlens for entry. Is there a way to make PHP force a "nextLine()" if there is such a thing... does PHP recognize return delimits?
Thank you!
// The string you are searching for
$package = 'packageB';
// Get the file into an array
$data = file('myfile.txt');
// Loop the data
for ($i = 0, $found = FALSE; isset($data[$i]); $i++) {
if (trim($data[$i]) == "BUILD: $package") { // We found the one we're looking for
echo trim($data[++$i]); // Echo the next line
$found = TRUE;
break; // Stop looping
}
}
if ($found) {
echo "<br />\nI found the URL on line $i";
} else {
echo "I didn't find it!";
}
file() gets the file data as an array where each element is one line of the file, unlike a single string like file_get_contents() returns.
You can do a regex with the /m modifier which makes it match across multiple lines, then use a parenthesized pattern to capture the line following the match:
if (preg_match_all('/BUILD: packageB\n(.+)\n/m', file_get_contents('file.txt'), $match)) {
foreach ($match[1] as $match) {
echo "$match\n";
}
}
Outputs:
URL: www.package-b.com
If you are open to alternative methods, then here is a simpler/faster solution.
builds.php
<?php
$builds=array("packageA"=>"www.package-a.com",
"packageB"=>"www.package-b.com",
"packageC"=>"www.package-c.com",
"packageD"=>"www.package-d.com");
?>
OtherScript.php
<?php
if(isset($_POST['package'])){
include('./builds.php');
if(array_key_exists($_POST['package'], $builds)){
$notice="You Selected: ".$_POST['package']." Url:".$builds[$_POST['package']];
}else{
$notice="Package Not Found";
}
}
echo (isset($_POST['package']))?$notice:'';
?>