Php removing specific special character and php algorithm ideas - php

so I ended up with this project, that,due to my opinion, is some levels greater than my skills, so I would like you to help me.
This project's functionality is to write some words in those 4 columns,which have to be combined.The words that are in the same column mustn't be combined. You can only combine words with the rest of the columns.
I will give you the full code so you can see what I have done.
The second question I have is how you delete a special character(in this case, the "\n")
<?php
if(isset($_POST['submit']))
{
if(isset($_POST["separator"])){$separator= $_POST["separator"];}
if(isset($_POST["match"])){$matchType = $_POST["match"];$matchArr = array();
foreach($matchType as $match)
{
$matchArr = $match;
}}
$j=0;
$columnCount=array();
$wordArr[] = array();
$wordArrRows[] = array();
$protasi="";
$wordsCombinations = 1;
$wordsCounter = 0;
for($i=0; $i<4; $i++)
{ $words=0;
$enterChar=0;
if(isset($_POST["in$i"]) && !empty($_POST["in$i"]))
{
$input=$_POST["in$i"];
$enterChar = substr_count($input,"\n");
$words= $enterChar+1;
if($words>0)
{
$wordArr[$j]= explode("\n",$input);
$wordArrRows[$j]= $words;
$j++;
}
$wordsCombinations*=$words;
}
}
$i2=0;
$columnCounter = array_fill(0, $j, "0");
while($wordsCounter < $wordsCombinations)
{
if($i2<sizeof($columnCounter) && $columnCounter[$i2] < $wordArrRows[$i2])
{
echo "grammi: ".$i2." <br>";
$i=0;
for($i=0; $i<$j; $i++)
{
//echo "wordArr[".$i."][".$columnCounter[$i]."]".$separator;
echo $wordArr[$i][$columnCounter[$i]]." ";
}
$columnCounter[$i2]++;
if($columnCounter[$i2] >= $wordArrRows[$i2] ){$columnCounter[$i2]=0;}
echo "<br>";
}
$i2++;
if($i2>=sizeof($columnCounter)){$i2=0;}
$wordsCounter++;
}
}
?>
(NOTE: don't use the radio buttons or the check boxes, they're not functional).

EDIT
What is the expected result for that example?
The second question: trim() to delete "\n"

Related

how to write prefixed unique coupon code in php

I am trying to write prefixed unique coupon code for get the chance to be a intern at one company. It went well so far, my code is generating 250st, 10 length of codes every time I refresh the page. However, I am issuing a problem with prefixed part. Normally coupon code is looking like this, just one example "1SC476XY3B" but I want every code to start "AB" and then 8 length of code so total will be 10. Can you help me guys? All help will be appreciated, thanks.
<?php
function unique_coupon_codes($number_of_codes,$exclude_codes_array='',$code_length = 10)
{
$characters = "0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
$unique_codes = array();
for($j = 1 ; $j <= $number_of_codes; $j++)
{
$code = "";
for ($i = 1; $i <= $code_length; $i++)
{
$code .= $characters[mt_rand(0, strlen($characters)-1)];
}
if(!in_array($code,$unique_codes))
{
if(is_array($exclude_codes_array))
{
if(!in_array($code,$exclude_codes_array))
{
$unique_codes[$j] = $code;
}
else
{
$j--;
}
}
else
{
$unique_codes[$j] = $code;
}
}
else
{
$j--;
}
}
return $unique_codes;
}
echo '<h1>Unique Coupon Codes</h1>';
echo '<pre>';
print_r(unique_coupon_codes(250,'',10));
echo '</pre>';
It needs a minor change while initializing $code variable. Change $code = ""; to $code = "AB"; And call unique_coupon_codes function as
print_r(unique_coupon_codes(250, '', 8));
Here generate a unique code of 8 digits as you already have prefix AB of length 2 characters.
How about something like this? :-)
function unique_coupon_codes($number_of_codes,$exclude_codes_array=[],$code_length = 10, $code_prefix="") {
$characters="0123456789QWERTYUIOPASDFGHJKLZXCVBNM";
$unique_codes = array();
for($i=1;$i<=$number_of_codes;$i++) {
$code="";
for($o=1;$o<=$code_length;$o++) {
$code .= $characters[mt_rand(0, strlen($characters)-1)];
}
if(in_array($code, $unique_codes) || in_array($code, $exclude_codes_array)) {
$i--;
} else {
$unique_codes[$i] = $code_prefix.$code;
}
}
return $unique_codes;
}
echo '<h1>Unique Coupon Codes</h1>';
echo '<pre>';
print_r(unique_coupon_codes(250,'',8, 'AB'));
echo '</pre>';

Is there anyway to repeat the biggest segment of continuous segment of repeat using php?

I want to put the input like "RKKRRRRK" and try to get the output like largest continuous segment.. Suppose my input may be "RKKKR" then my program will display 'KKK' is the largest continuous segment.. and then it also display the count is 3..
I've already write the code for counting 'R' values.. now i want this program also... need help anyone help me.. thanks in advance.
Here the code:-
<?php
function numberOfR($string1)
{
for($i=0;$i <strlen($string1);$i++)
{
if($string1[$i]!='K')
{
$count++;
}
}
return $count;
}
$return_value= numberOfR("RKKRK");
echo "R's count is:";
echo $return_value;
?>
<?php
function getLongetSegment($string) {
$currentSegmentChar='';
$currentSegment="";
$biggestSegment="";
$current_length=0;
$biggest_length=0;
for($i=0;$i<strlen($string);$i++) {
$char = $string[$i];
if($char != $currentSegmentChar || $currentSegmentChar == '') {
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
$biggest_length = $current_length;
}
$currentSegmentChar = $char;
$currentSegment = $char;
$current_length = 1;
}
elseif($currentSegmentChar != '') {
$currentSegment .= $char;
$current_length++;
}
}
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
}
return array("string" => $biggestSegment,"length" => $biggest_length);
}
print_r(getLongetSegment("RKKRGGG"));
?>
Result: GGG
You can use preg_match_all over here as
preg_match_all('/(.)\1+/i','RKKRRRRK',$res);
usort($res[0],function($a,$b){
return strlen($b) - strlen($a);
});
echo $res[0][0];
Not sure if I understood this quite right. Something like this:
function maxCharSequece($string1)
{
$maxSeq = $seq = 0;
$maxChar = $lastChar = null;
for( $i = 0; $i < strlen($string1); $i++ )
{
$c = $string1[$i];
if (!$lastChar) $lastChar = $c;
if ( $lastChar == $c ){
if ( ++$seq > $maxSeq ) $maxChar = $lastChar;
}
else {
$maxSeq = $seq;
$seq = 0;
}
}
return $maxChar;
}
You can use preg_replace_callback to receive all continuous segments and select the longest
$sq = '';
preg_replace_callback('/(.)\1+/',
function ($i) use (&$sq) {
if(strlen($i[0]) > strlen($sq)) $sq = $i[0];
}, $str);
echo $sq . " " . strlen($sq);

Why is strlen calculating the length is two higher than the length actually is?

I have the following code:
<?php
if (!isset($_SESSION["word"])) {
$dictionary_file = new SplFileObject("dictionary.txt");
$dictionary_file->seek(rand(0, 80367));
$_SESSION["word"] = $dictionary_file->current();
$_SESSION["word_progress"] = "";
for ($i = 0; $i < strlen($_SESSION["word"]); $i++) {
$_SESSION["word_progress"] .= "_";
}
echo strlen($_SESSION["word"]);
echo $_SESSION["word"];
}
else {
if (isset($_GET["guess"])) {
// If their guessed letter is in the word
if (stripos($_SESSION["word"], $_GET["guess"]) !== false) {
$occurrence_points = strposall($_SESSION["word"], $_GET["guess"]);
$progress = $_SESSION["word_progress"];
foreach ($occurrence_points as $values) {
$progress[$values] = $_GET["guess"];
}
$_SESSION["word_progress"] = $progress;
}
}
}
?>
I randomly generate a word from a file. Say it generates "bubble". The length is 6, but it will report 8, even after printing it out and confirming the word is indeed bubble. Why is this?
the randomly generated word might be adding whitespace. do a trim()
$_SESSION["word"] = trim($dictionary_file->current());

Mysql search string

I have a search box that will search for a keyword in the field : description
then return results. its done in mysql and php.
the description can go from 10 to 600 characters long. I would like to return only a part of result.
for example :
I am searching for the keyword= John
instead of displaying the whole field description as the result I want to see the sentence where the keyword is found only: ... Hello my name is john and I ...
not the whole paragraph.
I can use sql or php whichever one is better. I tried substring but failed implementing it any example would be great.
SELECT SUBSTR(description,2,100)
FROM screenplays
WHERE lower(description) like '% $search_word_fix %'
I thought by query, it will hamper performance. Because of string calculations. So I have done this by php substr function logic.
SELECT description
FROM screenplays
WHERE lower(description) like '% $search_word_fix %'
//$description will have longer string.
//$short_string will have shorter string.
$short_string=get_less_string($description,'john',20);
function get_less_string($string,$key,$num){
$desc=explode($key,$string);
$left='...'.substr($desc[0], strlen($desc[0])-$num,$num);
$right=substr($desc[1],0,$num).'...';
$final_string=$left.$key.$right;
return $final_string;
}
if you want to use php.. I had written a function few months back. It searches for keywords in a text and returns a string with 'bold' keywords. Hope this helps.
$str = 'I have a search box that will search for a keyword in the field : description then return results. its done in mysql and php. the description can go from 10 to 600 characters long. I would like to return only a part of result. for example : I am searching for the keyword= John instead of displaying the whole field description as the result I want to see the sentence where the keyword is found only: ... Hello my name is john and I ... not the whole paragraph.
I can use sql or php whichever one is better. I tried substring but failed implementing it any example would be great.';
$search = array();
$search[] = "example";
echo descriptionSearch($str,$search);
function descriptionSearch($desc,$words,$max_number_words = 30)
{
$descs = explode(" ",$desc);
$positions = array();
$i = 0;
foreach($words as $w)
{
$j = 0;
foreach($descs as $d)
{
$w = strtolower(trim($w));
$d = strtolower(trim($d));
if(strpos($d,$w) !== false)
{
$positions[] = $j;
$descs[$j] = str_replace($w,"<span style='font-weight: bold;'>".$d."</span>",$d);
}
$j++;
}
$i++;
}
$max = 0;
if(sizeof($positions) > 0)
{
foreach($positions as $j)
{
if($max < 4)
{
$i = $j -5;
if($i < 0)
{
$i = 0;
}
while($i < ($j+10))
{
$toreturn .= $descs[$i]." ";
$i++;
}
$toreturn .= " ...";
$max++;
}
}
}
else
{
for($i=0; $i < $max_number_words; $i++)
{
$toreturn .= $descs[$i]." ";
}
}
return $toreturn;
}
You CAN do it either way, and both will be about as efficient. PHP is probably a better more flexible solution, but just for kicks I tried to do it in MySQL, to see how it would work
SELECT SUBSTR(
description,
if(INSTR(description, '$search_word_fix') - 10 < 0,
0,
(INSTR(description, '$search_word_fix') - 10)),
if(
INSTR(description, '$search_word_fix') + 10 >
length(description),
length(description),
NSTR(description, '$search_word_fix') + 10))
FROM screenplays
WHERE lower(description) LIKE '% $search_word_fix %'
Modified answer, This can search better. In this example. I am searching for 'for example' or 'john'
$str = 'I have a search box that will search for a keyword in the field : description then return results. its done in mysql and php. the description can go from 10 to 600 characters long. I would like to return only a part of result. for example : I am searching for the keyword= John instead of displaying the whole field description as the result I want to see the sentence where the keyword is found only: ... Hello my name is john and I ... not the whole paragraph.
I can use sql or php whichever one is better. I tried substring but failed implementing it any example would be great.';
$search = array();
$search[] = "for example";
$search[] = "john";
echo descriptionSearch($str,$search);
function descriptionSearch($desc,$words,$max_number_words = 30)
{
$positions = array();
$i = 0;
foreach($words as $w)
{
$w = strtolower(trim($w));
$d = strtolower(trim($d));
if(strpos($desc,$w) !== false)
{
$positions[] = strpos($desc,$w);
$desc = str_replace($w,"<span style='font-weight: bold;'>".substr($desc,strpos($desc,$w),strlen($w))."</span>",$desc);
}
$i++;
}
$max = 0;
if(sizeof($positions) > 0)
{
foreach($positions as $j)
{
if($max < 4)
{
$i = $j -16;
if($i < 0)
{
$i = 0;
}
$toreturn .= substr($desc,$i,80);
$toreturn .= " ...";
$max++;
}
}
}
else
{
$descs = explode(" ",$desc);
for($i=0; $i < $max_number_words; $i++)
{
$toreturn .= $descs[$i]." ";
}
}
return $toreturn;
}

variable increment doesn't work

When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.

Categories