case selection based on pregmatch - php

I have a form that when a url is placed in the form and the button is clicked the URL is process and based on the pregmatch it extracts a URL. When a match is found for one of them the others return an error Notice: Undefined offset: 1 how can i make it so that if a match is found for one the others are not giving an error?
if ( !isset( $_GET['go'] ) ) return;
$userLink = $_GET['go'] ;
if ( !$userLink ) return;
$data = file_get_contents($userLink);
preg_match("#^(?:\s)*var url = '(.*)';#mi",$data, $parsed1);
preg_match("#^(?:\s)*self.location = '(.*)';#mi",$data, $parsed2);
preg_match("#^(?:\s)*window.location = \"(.*)\";#mi",$data, $parsed3);
preg_match("#^(?:\s)*Lbjs.TargetUrl = '(.*)';#mi",$data, $parsed4);
preg_match("#^(?:\s)*linkDestUrl = '(.*)';#mi",$data, $parsed5);
echo 'var.url - ' . $parsed1[1] . '<br>';
echo 'self.location - ' . $parsed2[1] . '<br>';
echo 'window.location - ' . $parsed3[1] . '<br>';
echo 'Lbjs.TargetUrl - ' . $parsed4[1] . '<br>';
echo 'linkDestUrl - ' . $parsed5[1];

I'm presuming only one of the URL types is going to match, not two or more?
if ( !isset( $_GET['go'] ) ) return;
$userLink = $_GET['go'] ;
if ( !$userLink ) return;
$data = file_get_contents($userLink);
$array = array(
'var url',
'self.location',
'window.location',
'Lbjs.TargetUrl',
'linkDestUrl',
);
foreach ($array as $value)
{
if (preg_match("#^(?:\s)*($value) = '(.*)';#mi",$data, $parsed))
{
break;
}
}
echo $parsed[1] . ' - ' . $parsed[2] . '<br>';

All you need to do is check whether the element is set before printing:
echo 'var.url - ' . (isset($parsed1[1]) ? $parsed[1] : 'not found') . '<br>';
echo 'self.location - ' . (isset($parsed1[2]) ? $parsed[2] : 'not found') . '<br>';
echo 'window.location - ' . (isset($parsed1[3]) ? $parsed[3] : 'not found') . '<br>';
echo 'Lbjs.TargetUrl - ' . (isset($parsed1[4]) ? $parsed[4] : 'not found') . '<br>';
echo 'linkDestUrl - ' . (isset($parsed1[5]) ? $parsed[5] : 'not found');

You can try to catch the result of preg_match, which will return 0 if no matches are found. From the php docs:
preg_match() returns the number of times pattern matches. That will be
either 0 times (no match) or 1
Something like:
if(preg_match("#^(?:\s)*var url = '(.*)';#mi",$data, $parsed1)) {
if(!empty($parsed1[1])) { echo 'var.url - ' . $parsed1[1] . '<br>'; }
}

You can put a # before each of your preg_match statements. # suppresses error messages, so be careful where you use it.
#preg_match("#^(?:\s)*var url = '(.*)';#mi",$data, $parsed1);

if (preg_match("#^(?:\s)*(var url|self.location|window..location|Lbjs.TargetUrl|linkDestUrl) = ['\"](.*)[\"'];#mi", $data, $parsed)) {
echo $parsed[1], " - ", $parsed[2];
} else {
echo "no matches found at all";
}

Related

PHP: How do I change a variable dependent on another variable? (Newbie stuff)

I'm pretty new to webcoding and would like to improve a bit in php, but I'm already stuck :/
What I am trying to do is to have a sentence like
"Simon likes apples"
Now I have an input form for the name so I can choose the name. So it looks like
"$name likes apples"
<table>
<tr>
<td><input type="text" id="name1" name="name1"></td>
<td><input type="submit" id="submit" name="submit" value="Apply"></td>
</tr>
</table>
</div>
<div id="text">
<?php
if(isset($_REQUEST['submit'])) {
$name1 = $_REQUEST['name1'];
echo "$name1 likes apples.";
}
?>
</div>
</form>
Everything fine till now. Whatever name I type in replaces $name. Now what I want to do is to change the "likes" to "like" whenever i type in a pronoun (I, You, They etc.), which makes sense obviously. Now here is where I don't know what to do. My current code (which doesnt work) looks like this:
<?php
if(isset($_REQUEST['submit'])) {
$name1 = $_REQUEST['name1'];
if ($name1 = "I", "You") {
$verb = "like";
}
else {
$verb = "likes";
}
echo "$name1 $verb apples";
}
?>
Also is there a way to make it case insensitive?
there are few problems in your code .
single = means SET my variable to whatever string is after . so if you want to see if your variable is equal to a string like You , you have to use == , it will return true or false .
now we want to say if my variable was You or I , change my second variable to like . thats gonna be the output :
if ($name1 == "I" || $name1 == "You") {
$verb = "like";
}
else {
$verb = "likes";
}
so now it says if $name1 was equal to I OR(||) $name1 was equal to You , change the $verb to like .
we use || as OR and && as AND.
if you want echo variables and string you should use . as split between your variable and string . so it will be like this :
echo $name1 . $verb . "apples";
it's kind of like + but not in a math way , it just means add .
UPDATE
yes . there is a way to check your string case insensitive . you have to use strcasecmp() .
in your code , it should be like :
if (strcasecmp($name1,"I") == 0 || strcasecmp($name1,"You") == 0 ) {
$verb = "like";
}
else {
$verb = "likes";
}
Case insensitive replacement, $lut table defines what should be replaced with what. You may place it inside the replaceMe function if you don't want to change it over time.
Code:
<?php
$lut = [
'like' => [
'I',
'You',
'They',
'We',
],
'likes' => [
'she',
'he',
'it',
'someone',
'somebody',
],
];
function replaceMe(string $name, array $lut) : string
{
foreach ($lut as $key => $value) {
$nameLower = strtolower($name);
$valueLowerArr = array_map(
function($input) {
return strtolower($input);
},
$value
);
if (in_array($nameLower, $valueLowerArr)) {
return strtolower($key);
}
}
return '';
}
$name = 'She';
echo "$name = " . replaceMe($name, $lut) . '<br>' . PHP_EOL;
$name = 'I';
echo "$name = " . replaceMe($name, $lut) . '<br>' . PHP_EOL;
$name = 'iT';
echo "$name = " . replaceMe($name, $lut) . '<br>' . PHP_EOL;
$name = 'TheY';
echo "$name = " . replaceMe($name, $lut) . '<br>' . PHP_EOL;
$name = 'nobody';
echo "$name = " . replaceMe($name, $lut) . '<br>' . PHP_EOL;
Gives Result:
She = likes<br>
I = like<br>
iT = likes<br>
TheY = like<br>
nobody = <br>

Alphabetize Petfinder API List

I'm using the Petfinder API for Wordpress plugin. The plugin defaults to listing animals based on how old the Petfinder entries are, from oldest to newest. I'm trying to figure out a way to either do newest to oldest, or alphabetize based on animal names.
The data is loaded via the following code:
function get_petfinder_data($api_key, $shelter_id, $count, $pet = '') {
// If no specific pet is specified
if ( $pet == '' ) {
// Create request URL for all pets from the shelter
$request_url = 'http://api.petfinder.com/shelter.getPets?key=' . $api_key . '&count=' . $count . '&id=' . $shelter_id . '&status=A&output=full';
}
// If a specific pet IS specified
else {
// Create a request URL for that specific pet's data
$request_url = 'http://api.petfinder.com/pet.get?key=' . $api_key . '&id=' . $pet;
}
// Request data from Petfinder
$petfinder_data = #simplexml_load_file( $request_url );
// If data not available, don't display errors on page
if ($petfinder_data === false) {}
return $petfinder_data;
And the code that creates the list looks like this:
function get_all_pets($pets) {
foreach( $pets as $pet ) {
// Define Variables
$pet_name = get_pet_name($pet->name);
$pet_type = get_pet_type($pet->animal);
$pet_size = get_pet_size($pet->size);
$pet_age = get_pet_age($pet->age);
$pet_gender = get_pet_gender($pet->sex);
$pet_options = get_pet_options_list($pet);
$pet_description = get_pet_description($pet->description);
$pet_photo_thumbnail = get_pet_photos($pet, 'medium');
$pet_photo_all = get_pet_photos ($pet, 'large', false);
$pet_more_url = get_site_url() . '/adopt/adoptable-dogs/?view=pet-details&id=' . $pet->id;
$pet_pf_url = 'http://www.petfinder.com/petdetail/' . $pet->id;
// Create breed classes
$pet_breeds_condensed = '';
foreach( $pet->breeds->breed as $breed ) {
$pet_breeds_condensed .= pet_value_condensed($breed) . ' ';
}
// Create options classes
$pet_options_condensed = '';
foreach( $pet->options->option as $option ) {
$option = get_pet_option($option);
if ( $option != '' ) {
$pet_options_condensed .= pet_value_condensed($option) . ' ';
}
}
// Compile pet info
// Add $pet_options and $pet_breeds as classes and meta info
$pet_list .= '<div class="vc_col-sm-3 petfinder ' . pet_value_condensed($pet_age) . ' ' . pet_value_condensed($pet_gender) . ' ' . $pet_breeds_condensed . ' ' . $pet_options_condensed . '">' .
'<div class="dogthumbnail">' .
'' . $pet_photo_thumbnail . '<br>' .
'</div>' .
'<a class="dogname" href="' . $pet_more_url . '">' . $pet_name . '</a><br>' .
'<span> ' . $pet_age . ' • ' . $pet_gender . '<br>' .
'<div class="dogbreed">' . $pet_breeds_condensed . '</div>' .
'<a class="morelink" href="' . $pet_more_url . '">Learn More <i class="fas fa-angle-right"></i></a><br>' .
'</div>';
}
// Return pet list
return $pet_list;
Here's an example of the XML that the Petfinder API spits out (right now there are 25 pet entries in the full thing):
<petfinder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://api.petfinder.com/schemas/0.9/petfinder.xsd">
<header>
<version>0.1</version>
<timestamp>2018-06-11T17:32:34Z</timestamp>
<status>
<code>100</code>
<message/>
</status>
</header>
<lastOffset>25</lastOffset>
<pets>
<pet>
<id>31035385</id>
<shelterId>IL687</shelterId>
<shelterPetId/>
<name>Chanel</name>
<animal>Dog</animal>
<breeds>...</breeds>
<mix>yes</mix>
<age>Adult</age>
<sex>F</sex>
<size>M</size>
<options>...</options>
<description>...</description>
<lastUpdate>2014-12-14T17:59:49Z</lastUpdate>
<status>A</status>
<media>...</media>
<contact>...</contact>
</pet>
</pets>
</petfinder>
I'd like to sort all entries by either "name" or "lastUpdate". I've been looking at a lot of posts about sorting XML element objects but they either don't seem to work or I can't figure out how to apply them specifically to my code. I'm not super well-versed in this stuff, so any assistance is much appreciated!!
After a LOT of research and trial and error, I figured out how to organize alphabetically by animal name. Posting this in case anybody is ever trying to figure out the same.
First of all, I was wrong in my assumption of which sections I might need to be editing. It was actually line 723 of the plugin file. Here's how I modified the code for that section:
// Display a list of all available dogs
else {
// Access Petfinder Data
$petfinder_data = get_petfinder_data($api_key, $shelter_id, $count);
// If the API returns without errors
if( $petfinder_data->header->status->code == '100' ) {
// If there is at least one animal
if( count( $petfinder_data->pets->pet ) > 0 ) {
//Sort list of dogs ALPHABETICALLY by NAME
$petSXE = $petfinder_data->pets->children();
$petArray = array();
foreach($petSXE->pet as $d) {
$petArray[] = $d;
}
function name_cmp($a, $b) {
$va = (string) $a->name;
$vb = (string) $b->name;
if ($va===$vb) {
return 0;
}
return ($va<$vb) ? -1 : 1;
}
usort($petArray, 'name_cmp');
$pets = $petArray;
// Compile information that you want to include
$petfinder_list = get_type_list($pets).
get_age_list($pets) .
get_size_list($pets) .
get_gender_list($pets) .
get_options_list($pets) .
get_breed_list($pets) .
get_all_pets($pets);
}
This is adapting the solution I found in this thread: sort xml div by child node PHP SimpleXML

Getting a variable that exists sometimes and doesn't at other times

My problem is in my code I'm having problems with it calculating something with a variable that does not exists some times and some times does.
I want it to give me back number of deaths if empty '0' if not prints me what is in the variable, but for some reason i get this:
E_NOTICE : type 8 -- Undefined property: stdClass::$numDeaths -- at
line 66 E_WARNING : type 2 -- Division by zero -- at line 71
here is my code:
<?php
$apiKey = 'e9044828-20e3-46cc-9eb5-545949299803';
$summonerName = 'tamini';
$new = rawurlencode($summonerName);
$news = str_replace(' ', '', $summonerName);
$str = strtolower($news);
// get the basic summoner info
$result = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/' . $new . '?api_key=' . $apiKey);
$summoner = json_decode($result)->$str;
$id = $summoner->id;
// var_dump($summoner);
?>
<?php
$clawzz = file_get_contents('https://euw.api.pvp.net/api/lol/euw/v1.3/game/by-summoner/' . $id . '/recent?api_key=' . $apiKey);
$gazazz = json_decode($clawzz);
?>
<?php
$entrieszz = $gazazz->games;
usort($entrieszz, function($ac,$bc){
return $bc->createDate-$ac->createDate;
});
foreach($entrieszz as $statSummaryzz){
$gamemodekillz = $statSummaryzz->stats->championsKilled;
$gamemodedeathz = $statSummaryzz->stats->numDeaths;
$gamemodeassistz = $statSummaryzz->stats->assists;
$kdamatchhistoryeach = ($gamemodekillz + $gamemodeassistz) / $gamemodedeathz;
echo ' <br>';
echo $gamemodekillz;
echo ' <br>';
if ($gamemodedeathz == 0){
echo '0';
}
else {
echo $gamemodedeathz ;
}
echo ' <br>';
echo $gamemodeassistz;
echo ' <br>';
if ($gamemodedeathz == 0){
echo 'Perfect Score';
}
else {
echo $kdamatchhistoryeach ;
}
?>
You need to check if the value exist:
if( isset($statSummaryzz->stats) && isset($statSummaryzz->stats->numDeaths) ) {
$gamemodedeathz = $statSummaryzz->stats->numDeaths;
}

how i get the information

I have this script and i need this result:
Numelem / Title / ElmPoste
foreach ( $jobPrintingInfos as $jobprinting_index => $jobprinting ) {
$machine = $jobprinting ['ElmPoste'];
//var_dump($machine);
// var_dump($machine);
}
foreach ( $GetJobResult->Components->Component as $component_index => $component ) {
$quote_support ='';
$quote_impression = '';
$quote_title = ($component->NumElem) . ' / ' . $component->Title . ' ' .$machine. "\r\n";
var_dump($quote_title);
}
but when i do var_dump($quote_title) i have the last machine not all the machine :such as
1/Dessus /Nesspresso
2/Inter/Nesspresso
3/Assem/Nesspresso
Thanks in advance
i dont know the idea behind that script... but if you want that $quote_title <-- is one long String then you need to add a .
like this:
$quote_title .= ($component->NumElem) . ' / ' . $component->Title . ' ' .$machine. "\r\n";
--------------------^
or as array, then its easyer to use a for loop

Return smallest value of an array in a function through a foreach loop?

I have an array and I would like to return just the lowest value of the array but no matter what I try I get error or I get the full list. Help
function myForEachLoop()
$StudentPopulation = array('BSU'=>19664, 'CSU'=>25500, 'SDSU'=>35887, 'UHM'=>20000,
'AFA'=>4000, 'UNLV'=>28000, 'FS'=>21389, 'UNR'=>17000, 'UNM'=>25767, 'UW'=>13476);
ksort($StudentPopulation);
foreach($StudentPopulation as $aSchool => $aPop)
{
$output .= '<strong>School:</strong> ' . ($aSchool) . '<strong> Population:</strong> ' . $aPop . '<br />';
}
return $output;
I want to return just "School: AFA" Population: 4000".
This question has almost no sense, but if you really need it to be done try:
function myForEachLoop(&$StudentPopulation) {
ksort($StudentPopulation);
$min = 'NO_MIN';
foreach($StudentPopulation as $aSchool => $aPop)
{
if($min=='NO_MIN' || $aPop<$min) {
$output = '<strong>School:</strong> ' . ($aSchool) . '<strong> Population:</strong> ' . $aPop . '<br />';
$min = $aPop;
}
}
return $output;
}
$StudentPopulation = array('BSU'=>19664, 'CSU'=>25500, 'SDSU'=>35887, 'UHM'=>20000,
'AFA'=>4000, 'UNLV'=>28000, 'FS'=>21389, 'UNR'=>17000, 'UNM'=>25767, 'UW'=>13476);
echo myForEachLoop($StudentPopulation);
Try this:
function myForEachLoop()
{
$StudentPopulation = array('BSU'=>19664, 'CSU'=>25500, 'SDSU'=>35887, 'UHM'=>20000,
'AFA'=>4000, 'UNLV'=>28000, 'FS'=>21389, 'UNR'=>17000, 'UNM'=>25767, 'UW'=>13476);
ksort($StudentPopulation);
$lowestValue = min($studentPopulation); // 4000
$lowestValueIndex = array_keys($studentPopulation, min($studentPopulation)); // AFA
$output .= '<strong>School:</strong> ' . ($lowestValueIndex) . '<strong> Population:</strong> ' . $lowestValue. '<br />'
return $output;
}

Categories