Question: A string is said to be complete if it contains all the characters from a to z. Given a string, check if it complete or not.
Input
First line of the input contains the number of strings N. It is followed by N lines each contains a single string.
Output
For each test case print "YES" if the string is complete, else print "NO"
Constraints
1 <= N <= 10
The length of the string is at max 100 and the string contains only the characters a to z
YOU CAN CHECK HERE http://www.hackerearth.com/problem/algorithm/complete-string-4/
When i submit the PHP code , it shows the result is wrong
<?php
$allowedString = array('random','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
function execute($fileName = "3\nwyyga\nqwertyuioplkjhgfdsazxcvbnm\nejuxggfsts"){
global $allowedString;
//$handle = fopen($fileName, 'r');
$l=0;
$text = array();
$text = explode("\n", $fileName);
$z=0;
// print_r($text);
if ($text[0]>=1 && $text[0]<=10){
for($i=1;$i<=$text[0];$i++){
if(strlen($text[$i])>=26 && strlen($text[$i])<=100 ){
$count = 0;
for($z=1;$z<27;$z++){
$pos = strpos($text[$i], $allowedString[$z]);
if($pos === false){
continue;
}else{
$count++;
}
}
if($count == 26){
echo 'YES'."<br>";
}else{
echo 'NO'."<br>";
}
}else{
echo 'NO'."<br>";
}
}
}
}
execute();
?>
After a quick look at the page, it seems that the site is STDIO (Standard Input/Output) for input and output data rather than files. So, you shouldn't read/write data to a file.
Here is some code:
<?php
//This will input a file from Standard Input
$line = trim(fgets(STDIN));
//This will output the string to Standard Output
fwrite(STDOUT, $output);
?>
Related
I'm trying to develop a PHP application where it takes comments from users and then match the string to check if the comment is positive or negative. I have list of negative words in negative.txt file. If a word is matched from the word list, then I want a simple integer counter to increment by 1. I tried the some links and created the a code to check if the comment has is negative or positive but it is only matching the last word of the file.Here's the code what i have done.
<?php
function teststringforbadwords($comment)
{
$file="BadWords.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
$newline_ele = "\n";
$data_split = explode($newline_ele, $fread);
$new_tab = "\t";
$outoutArr = array();
//process uploaded file data and push in output array
foreach ($data_split as $string)
{
$row = explode($new_tab, $string);
if(isset($row['0']) && $row['0'] != ""){
$outoutArr[] = trim($row['0']," ");
}
}
//---------------------------------------------------------------
foreach($outoutArr as $word) {
if(stristr($comment,$word)){
return false;
}
}
return true;
}
if(isset($_REQUEST["submit"]))
{
$comments = $_REQUEST["comments"];
if (teststringforbadwords($comments))
{
echo 'string is clean';
}
else
{
echo 'string contains banned words';
}
}
?>
Link Tried : Check a string for bad words?
I added the strtolower function around both your $comments and your input from the file. That way if someone spells STUPID, instead of stupid, the code will still detect the bad word.
I also added trim to remove unnecessary and disruptive whitespace (like newline).
Finally, I changed the way how you check the words. I used a preg_match to split about all whitespace so we are checking only full words and don't accidentally ban incorrect strings.
<?php
function teststringforbadwords($comment)
{
$comment = strtolower($comment);
$file="BadWords.txt";
$fopen = fopen($file, "r");
$fread = strtolower(fread($fopen,filesize("$file")));
fclose($fopen);
$newline_ele = "\n";
$data_split = explode($newline_ele, $fread);
$new_tab = "\t";
$outoutArr = array();
//process uploaded file data and push in output array
foreach ($data_split as $bannedWord)
{
foreach (preg_split('/\s+/',$comment) as $commentWord) {
if (trim($bannedWord) === trim($commentWord)) {
return false;
}
}
}
return true;
}
1) Your storing $row['0'] only why not others index words. So problem is your ignoring some of word in text file.
Some suggestion
1) Insert the text in text file one by one i.e new line like this so you can access easily explode by newline to avoiding multiple explode and loop.
Example: sss.txt
...
bad
stupid
...
...
2) Apply trim and lowercase function to both comment and bad string.
Hope it will work as expected
function teststringforbadwords($comment)
{
$file="sss.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
foreach(explode("\n",$fread) as $word)
{
if(stristr(strtolower(trim($comment)),strtolower(trim($word))))
{
return false;
}
}
return true;
}
I'm working in a company where I have this project to create a web application based on the products my company is making.
There is an inside server which contains all the data from my company. What I have to do is parse the data the oracle server is retrieving. It is retrieving .lst files which can be easily translated to .csv using Excel or some php packages.
I successfully imported the Clients table into my MySQL database using the LOAD DATA INFILE command. But I'm running some issues when I want to parse the Articles table.
The columns/values aren't necessarily separated by semi-colons. To parse the data I'll have to say for example :
The first 6 characters are the Article ID
The next 35 characters are the description of the article
and so on...
Is there a way I could achieve this when using the LOAD DATA INFILE command, or should I format the file correctly using PHP then use this command and if so what could be the best approach?
Thanks guys, I hope I made myself clear since english isn't my primary language. :P
Edit : those are rows.
51016 51016 BOITE ORANGINA 33cls CASHS "24" 040430024000330 0000000000 1 01000000550009000 000000NNNNNN caisse 0000003750000000000001230
51019 51019 BOITE OASIS ORANGE CASHS "24" 33cl 040430024000330 0000000000 1 01000000550009000 000000NNNNNN caisse 0000003670000000000001230
The first line is getting parsed correctly while the second isnt.The double quote after 24 is being put into the next column. I just wanted to know if it was possible to do something about it, like deleting the double quotes.
A previous developer created an application to manage the articles, clients from the company. Unfortunately he cannot help me anymore but here is a ligne that describe a row.
import_a;Code_article;6;designation;35;designation2;35;Code_famille;2;Code_sousfamille;4;unite_condition;3;contenance;6/1000;Champ_vide;2;degre;4/10;champ_vide_6;6;Code_emballage;4;Champ_vide2;8;validite;1;Champ_vide3;7;code_tva;2;taux_tva;9/100;poids;6/1000;champ_vide4;19;montant_droits;6/1000;valide;1;rupture;1;edit_tarif;1;pre_commande;1;gratuit_autorise;1;trans_port;1;Champ_libre;1;caisse;15;prix_revient;9/100;stock;6/1;Champ_vide5;5;code_fournisseur;11/1
import_a => It's the filename you can just ignore that.
Then you have the name of the column followed by the number of characters. For example Code_articles is composed of 6 characters and so on.
You can also just ignore the duplicate ID Key at the beginning. But in total there should be 31 columns.
You can use this perl script to start your testing. The most important thing is the adjust the $def line according to your real data, until your get the correct result.
#!/usr/bin/perl
$input_file = "/tmp/a.lst";
$output_file = "/tmp/a.csv";
$testing = 1; #testing, print out directly first 100 lines
# we are using tab (#9) for the output csv file
$delim ="\t";
# output column header
$output_header = 1;
$defs= "import_a;Code_article;6;Code_article2;6;designation;29;designation2;35;Code_famille;2;Code_sousfamille;4;unite_condition;3;contenance;6/1000;Champ_vide;2;degre;4/10;champ_vide_6;6;Code_emballage;4;Champ_vide2;8;validite;1;Champ_vide3;7;code_tva;2;taux_tva;9/100;poids;6/1000;champ_vide4;19;montant_droits;6/1000;valide;1;rupture;1;edit_tarif;1;pre_commande;1;gratuit_autorise;1;trans_port;1;Champ_libre;1;caisse;15;prix_revient;9/100;stock;6/1;Champ_vide5;5;code_fournisseur;11/1";
my #input_fields, #input_fieldwidths, #input_fieldwidth_max, $input_field_no =0;
#defs= split(";",$defs);
$total_defs=$#defs;
$total_cols = 0;
$total_width = 0;
for($x=0; $x<$total_defs /2; $x++)
{
push(#input_fields, $defs[$x*2+1]);
$width = $defs[$x*2+2];
if($width=~/(.*)\/(.*)/){
$mw= $1;
$xw= $2;
}
else{
$mw = $width;
$xw= 0;
}
$total_width += $mw;
push(#input_field_widths,$mw);
push(#input_field_widths_max, $xw);
$total_cols ++;
}
if($testing){
for($x=1; $x<$total_cols; $x++)
{
print "$input_fields[$x]: $input_field_widths[$x]\n";
}
}
open(INPUT, $input_file) || die "Can not open input file";
open(OUTPUT, ">$output_file" ) || die "Can not open output file";
# this is the csv head
if($output_header){
print OUTPUT "$input_fields[0]";
for($x=1; $x<$total_cols; $x++)
{
print OUTPUT "\t$input_fields[$x]";
}
print OUTPUT "\n";
}
$lines=0;
foreach $l (<INPUT>)
{
chop($l);
$pos =0;
for($f=0; $f < $total_cols; $f++)
{
$val = substr($l, $pos, $input_field_widths[$f]);
print OUTPUT $delim if($pos);
print $delim if($pos && $testing);
print OUTPUT $val;
print $val if($testing);
$pos += $input_field_widths[$f];
}
print OUTPUT "\n";
print "\n" if($testing);
$lines++;
if($testing && $lines>100) { last;};
}
print $lines , " lines transformed\n";
close(INPUT);
close(OUTPUT);
Edit: for a comma separated quoted csv format:
#!/usr/bin/perl
$input_file = "/tmp/a.lst";
$output_file = "/tmp/a.csv";
# we are using tab (#9) for the output csv file
$delim =";";
$testing = 1; #testing, print out directly first 10 lines
$quote ="'";
# output column header
$output_header = 1;
$defs= "import_a;Code_article;6;Code_article2;6;designation;29;designation2;35;Code_famille;2;Code_sousfamille;4;unite_condition;3;contenance;6/1000;Champ_vide;2;degre;4/10;champ_vide_6;6;Code_emballage;4;Champ_vide2;8;validite;1;Champ_vide3;7;code_tva;2;taux_tva;9/100;poids;6/1000;champ_vide4;19;montant_droits;6/1000;valide;1;rupture;1;edit_tarif;1;pre_commande;1;gratuit_autorise;1;trans_port;1;Champ_libre;1;caisse;15;prix_revient;9/100;stock;6/1;Champ_vide5;5;code_fournisseur;11/1";
my #input_fields, #input_fieldwidths, #input_fieldwidth_max, $input_field_no =0;
#defs= split(";",$defs);
$total_defs=$#defs;
$total_cols = 0;
$total_width = 0;
for($x=0; $x<$total_defs /2; $x++)
{
push(#input_fields, $defs[$x*2+1]);
$width = $defs[$x*2+2];
if($width=~/(.*)\/(.*)/){
$mw= $1;
$xw= $2;
}
else{
$mw = $width;
$xw= 0;
}
$total_width += $mw;
push(#input_field_widths,$mw);
push(#input_field_widths_max, $xw);
$total_cols ++;
}
if($testing){
for($x=0; $x<$total_cols; $x++)
{
print "$input_fields[$x]: $input_field_widths[$x]\n";
}
}
open(INPUT, $input_file) || die "Can not open input file";
open(OUTPUT, ">$output_file" ) || die "Can not open output file";
# this is the csv head
if($output_header){
print OUTPUT "$input_fields[0]";
for($x=1; $x<$total_cols; $x++)
{
print OUTPUT "\t$input_fields[$x]";
}
print OUTPUT "\n";
}
$lines=0;
foreach $l (<INPUT>)
{
chop($l);
$pos =0;
for($f=0; $f < $total_cols; $f++)
{
$val = substr($l, $pos, $input_field_widths[$f]);
print OUTPUT $delim if($pos);
#print $delim if($pos && $testing);
print OUTPUT $quote, $val, $quote;
if($testing){
print $input_fields[$f] , "=", $val, "\n";
}
$pos += $input_field_widths[$f];
}
print OUTPUT "\n";
print "\n" if($testing);
$lines++;
if($testing && $lines>0) { last;};
}
print $lines , " lines transformed\n";
close(INPUT);
close(OUTPUT);
I am using the following code to place some ad code inside my content .
<?php
$content = apply_filters('the_content', $post->post_content);
$content = explode (' ', $content);
$halfway_mark = ceil(count($content) / 2);
$first_half_content = implode(' ', array_slice($content, 0, $halfway_mark));
$second_half_content = implode(' ', array_slice($content, $halfway_mark));
echo $first_half_content.'...';
echo ' YOUR ADS CODE';
echo $second_half_content;
?>
How can i modify this so that the 2 paragraphs (top and bottom) enclosing the ad code should not be the one having images. If the top or bottom paragraph has image then try for next 2 paragraphs.
Example: Correct Implementation on the right.
preg_replace version
This code steps through every paragraph ignoring those that contain image tags. The $pcount variable is incremented for every paragraph found without an image, if an image is encountered however, $pcount is reset to zero. Once $pcount reaches the point where it would hit two, the advert markup is inserted just before that paragraph. This should leave the advert markup between two safe paragraphs. The advert markup variable is then nullified so only one advert is inserted.
The following code is just for set up and could be modified to split the content differently, you could also modify the regular expression that is used — just in case you are using double BRs or something else to delimit your paragraphs.
/// set our advert content
$advert = '<marquee>BUY THIS STUFF!!</marquee>' . "\n\n";
/// calculate mid point
$mpoint = floor(strlen($content) / 2);
/// modify back to the start of a paragraph
$mpoint = strripos($content, '<p', -$mpoint);
/// split html so we only work on second half
$first = substr($content, 0, $mpoint);
$second = substr($content, $mpoint);
$pcount = 0;
$regexp = '/<p>.+?<\/p>/si';
The rest is the bulk of the code that runs the replacement. This could be modified to insert more than one advert, or to support more involved image checking.
$content = $first . preg_replace_callback($regexp, function($matches){
global $pcount, $advert;
if ( !$advert ) {
$return = $matches[0];
}
else if ( stripos($matches[0], '<img ') !== FALSE ) {
$return = $matches[0];
$pcount = 0;
}
else if ( $pcount === 1 ) {
$return = $advert . $matches[0];
$advert = '';
}
else {
$return = $matches[0];
$pcount++;
}
return $return;
}, $second);
After this code has been executed the $content variable will contain the enhanced HTML.
PHP versions prior to 5.3
As your chosen testing area does not support PHP 5.3, and so does not support anonymous functions, you need to use a slightly modified and less succinct version; that makes use of a named function instead.
Also, in order to support content that may not actually leave space for the advert in it's second half I have modified the $mpoint so that it is calculated to be 80% from the end. This will have the effect of including more in the $second part — but will also mean your adverts will be generally placed higher up in the mark-up. This code has not had any fallback implemented into it, because your question does not mention what should happen in the event of failure.
$advert = '<marquee>BUY THIS STUFF!!</marquee>' . "\n\n";
$mpoint = floor(strlen($content) * 0.8);
$mpoint = strripos($content, '<p', -$mpoint);
$first = substr($content, 0, $mpoint);
$second = substr($content, $mpoint);
$pcount = 0;
$regexp = '/<p>.+?<\/p>/si';
function replacement_callback($matches){
global $pcount, $advert;
if ( !$advert ) {
$return = $matches[0];
}
else if ( stripos($matches[0], '<img ') !== FALSE ) {
$return = $matches[0];
$pcount = 0;
}
else if ( $pcount === 1 ) {
$return = $advert . $matches[0];
$advert = '';
}
else {
$return = $matches[0];
$pcount++;
}
return $return;
}
echo $first . preg_replace_callback($regexp, 'replacement_callback', $second);
You could try this:
<?php
$ad_code = 'SOME SCRIPT HERE';
// Your code.
$content = apply_filters('the_content', $post->post_content);
// Split the content at the <p> tags.
$content = explode ('<p>', $content);
// Find the mid of the article.
$content_length = count($content);
$content_mid = floor($content_length / 2);
// Save no image p's index.
$last_no_image_p_index = NULL;
// Loop beginning from the mid of the article to search for images.
for ($i = $content_mid; $i < $content_length; $i++) {
// If we do not find an image, let it go down.
if (stripos($content[$i], '<img') === FALSE) {
// In case we already have a last no image p, we check
// if it was the one right before this one, so we have
// two p tags with no images in there.
if ($last_no_image_p_index === ($i - 1)) {
// We break here.
break;
}
else {
$last_no_image_p_index = $i;
}
}
}
// If no none image p tag was found, we use the last one.
if (is_null($last_no_image_p_index)) {
$last_no_image_p_index = ($content_length - 1);
}
// Add ad code here with trailing <p>, so the implode later will work correctly.
$content = array_slice($content, $last_no_image_p_index, 0, $ad_code . '</p>');
$content = implode('<p>', $content);
?>
It will try to find a place for the ad from the mid of your article and if none is found the ad is put to the end.
Regards
func0der
I think this will work:
First explode the paragraphs, then you have to loop it and check if you find img inside them.
If you find it inside, you try the next.
Think of this as psuedo-code, since it's not tested. You will have to make a loop too, comments in the code :) Sorry if it contains bugs, it's written in Notepad.
<?php
$i = 0; // counter
$arrBoolImg = array(); // array for the paragraph booleans
$content = apply_filters('the_content', $post->post_content);
$contents = str_replace ('<p>', '<explode><p>', $content); // here we add a custom tag, so we can explode
$contents = explode ('<explode>', $contents); // then explode it, so we can iterate the paragraphs
// fill array with boolean array returned
$arrBoolImg = hasImages($contents);
$halfway_mark = ceil(count($contents) / 2);
/*
TODO (by you):
---
When you have $arrBoolImg filled, you can itarate through it.
You then simply loop from the middle of the array $contents (plural), that is exploded from above.
The startingpoing for your loop is the middle, the upper bounds is the +2 or what ever :-)
Then you simply insert your magic.. And then glue it back together, as you did before.
I think this will work. even though the code may have some bugs, since I wrote it in Notepad.
*/
function hasImages($contents) {
/*
This function loops through the $contents array and checks if they have images in them
The return value, is an array with boolean values, so one can iterate through it.
*/
$arrRet = array(); // array for the paragraph booleans
if (count($content)>=1) {
foreach ($contents as $v) { // iterate the content
if (strpos($v, '<img') === false) { // did not find img
$arrRet[$i] = false;
}
else { // found img
$arrRet[$i] = true;
}
$i++;
} // end for each loop
return $arrRet;
} // end if count
} // end hasImages func
?>
[This is just an idea, I don't have enough reputation to comment...]
After calling #Olavxxx's method and filling your boolean array you could just loop through that array in an alternating manner starting in the middle: Let's assume your array is 8 entries long. Calculating the middle using your method you get 4. So you check the combination of values 4 + 3, if that doesn't work, you check 4 + 5, after that 3 + 2, ...
So your loop looks somewhat like
$middle = ceil(count($content) / 2);
$i = 1;
while ($i <= $middle) {
$j = $middle + (-1) ^ $i * $i;
$k = $j + 1;
if (!$hasImagesArray[$j] && !$hasImagesArray[$k])
break; // position found
$i++;
}
It's up to you to implement further constraints to make sure the add is not shown to far up or down in the article...
Please note that you need to take care of special cases like too short arrays too in order to prevent IndexOutOfBounds-Exceptions.
I'm currently using foreach loop to display the contents of a text file. However, I want to also display the whitespaces that precede the actual content of the line. How to do so?
$loop_var = 0;
foreach($lines as $line) {
$loop_var++;
if ($loop_var == 1) {
echo'<div id="h1">' . $line . '</div>';
}
if ($loop_var == 2) {
echo '<div id="h2">' . $line . '</div><br />';
}
if ($loop_var > 2) {
if ($loop_var == 3) { echo '<pre><div id="code">'; }
echo ($line) . "<br />";
}
}
echo '</pre></div>';
Now, if the textfile contains the following:
blah
blah
blah
blah
It is getting displayed as:
blah
blah
blah
blah
Use <pre> tag, and print the content of textfile into this.
example:
print '<pre>'.file_get_contents('filename.txt').'</pre>';
Line By line (With conditions)
$file = fopen('filename','r');
print '<pre>';
$counter = 0;
while( $line = fgets($file) ){
if( /*the condition comes here whitch line you want to print. example: */ $counter >= 2 ){
print $line;
}
if( /*the condition comes here where wants you end the printing. example: */ $counter >= 10 )
$counter++;
}
print '</pre>';
fclose($file);
When you read text from a file and output that text again, the whitespace is still there.
But: if you are outputting HTML, and viewing the output in a browser, the whitespace is ignored. That's just the normal way html is displayed by a browser.
Use your browser to view the HTML source code (e.g. CTRL-U in firefox) to check if this is the case.
If you want the whitespace to be displayed in your webpage you can use the pre-Tag, or use the CSS property "whitespace" http://www.w3schools.com/cssref/pr_text_white-space.asp.
<pre><?php echo $file_content ?></pre>
or
<p style="whitespace:pre;"><?php echo $file_content ?></p>
See demo here: http://jsfiddle.net/bjelline/CjXMe/
Well, you can brute-force it if you wish ... only in case you're really stuck!
1) Get the length of the string with strlen()
2) Run a loop on the characters in the string and check for a space with strpos
3) Concatenate an html space to an empty string and print before-hand
$str = " whatever is in here ... ";
$spaces = "";
for( $i=0; $i<strlen($str); $i++ ){
if( strpos( $str, ' ', $i ) ){
$spaces .= " ";
}
}
Write PHP script to search for a word in a text file (titled a.txt). Text file contains 50 words, each word is on 1 line. On the JavaScript side, a client types a random word in a text field and submits the word. The PHP script searches through the 50 words to find the correct word using a loop that runs until the word is found in the a .txt file. If the word is not found, an error message must appear stating that the word was not in the list.
The JavaScript part is correct but I'm having trouble with PHP:
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
$a = trim($x);
if(strcmp($s, $a) == 0)
print("<h1>" . $_POST["lname"] . " is in the list</h1>");
else
print("<h1>" . $_POST["lname"] . " is not in the list</h1>");
fclose($file);
?>
If it's only 50 words then just make an array out of it and check if it's in the array.
$file = file_get_contents('a.txt');
$split = explode("\n", $file);
if(in_array($_POST["lname"], $split))
{
echo "It's here!";
}
function is_in_file($lname) {
$fp = #fopen($filename, 'r');
if ($fp) {
$array = explode("\n", fread($fp, filesize($filename)));
foreach ($array as $word) {
if ($word == $lname)
return True;
}
}
return False;
}
You are not searching the "word" into your code, but maybe the code below will help you
$array = explode("\n",$string_obtained_from_the_file);
foreach ($array as $value) {
if ($value== "WORD"){
//code to say it has ben founded
}
}
//code to say it hasn't been founded
here is something fancy, regular expression :)
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match('/^' . $s . '$/im', $x) === true){
// word found do what you want
}else{
// word not found, error
}
remove the i from '$/im' if you do not want to the search to be case-insensitive
the m in there tells the parser to match ^$ to line endings, so this works.
here is a working example : http://ideone.com/LmgksA
You actually don't need to break apart the file into an array if all you're looking for is a quick existence check.
$file = fopen("a.txt","r") or die("File does not exist in the current folder.");
$s = $_POST["lname"];
$x = file_get_contents("a.txt");
if(preg_match("/\b".$s."\b/", $x)){
echo "word exists";
} else {
echo "word does not exists";
}
This matches any word token in a string.