PigLatin in PHP eroor - php

function PigLatin($sentence)
{
$vowelSufix = "way";
$consonantSufix = "ay";
$vowelArray = array('a','e','o','u','i');
$finalword;
$wordArray = explode(' ', $sentence);
foreach ($wordArray as $value)
{
$word = $value;
$consonant = $word[0];
if (in_array($word[0], $vowelArray))
{
$finalword = substr($word, 1). $word[0]. $vowelSufix. "<br />";
}
else
{
for ($i=1; $i <strlen($word) ; $i++)
{
if (in_array($word[$i], $vowelArray))
{
$finalword = substr($word, $i). $consonant. $consonantSufix . "<br />";
}
else
{
$consonant .= $word[$i];
}
}
}
if ($finalword[0] == $finalword[1])
{
return substr($finalword, 1);
}
$finalword .= $finalword;
}
var_dump($wordArray);
}
So basicly it is giveing me the follow errors "Uninitialized string offset".I know this error comes because i am useing the arrays not proberly but i am stuck, Can someone please help me?

Your script doesn't handle the case where $word is empty, which will happen if you have two spaces in a row in the sentence. If $word is an empty string, $word[0] will get the error you reported, because there is no such character in the string.
Change the loop to:
foreach ($wordArray as $word)
{
if ($word === '') {
continue;
}
This will skip empty words. Note also that you don't need separate variables $value and $word.

Related

I have code like this How to code print like this?

input name: DEVO AVIDIANTO PRATAMA
output: DAP
if the input three word , appears DAP
input name: AULIA ABRAR
output: AAB
if the input two words, appears AAB
input name: AULIA
output: AUL
  if the input one word, appears AUL
<?php
$nama = $_POST['nama'];
$arr = explode(" ", $nama);
//var_dump($arr);die;
$jum_kata = count($arr);
//echo $jum_kata;die;
$singkatan = "";
if($jum_kata == 1){
//print_r($arr);
foreach($arr as $kata)
{
echo substr($kata, 0,3);
}
}else if($jum_kata == 2) {
foreach ($arr as $kata) {
echo substr($kata,0,2);
}
}else {
foreach ($arr as $kata) {
echo substr($kata,0,1);
}
}
?>
how to correct this code :
else if($jum_kata == 2) {
foreach ($arr as $kata) {
echo substr($kata,0,2);
}
to print AAB?
As a variant of another approach. Put each next string over the previous with one step shift. And then slice the start of a resulting string
function initials($str, $length=3) {
$string = '';
foreach(explode(' ', $str) as $k=>$v) {
$string = substr($string, 0, $k) . $v;
}
return substr($string, 0, $length);
}
echo initials('DEVO AVIDIANTO PRATAMA'). "\n"; // DAP
echo initials('AULIA ABRAR'). "\n"; // AAB
echo initials('AULIA'). "\n"; // AUL
demo
You could do:
elseif ($jum_kata == 2) {
echo substr($kata[0],0,1);
echo substr($kata[1],0,2);
}
This will just get the first character of the first word, and then two characters from the next word.
You are returning two characters from each word which is why you get AUAB.

Comparing a value with previous value in a foreach loop with remove same value?

In a foreach statement,
remove duplicate value? i don't know how ask on this Q ?
This my code
$text = "ABC01
ABC02
ABC03
ABC04
ABC05
ABC06
";
$text = explode("\n",str_replace("\r", "", $text));
$text = array_filter($text, 'trim');
$previous = "";
foreach ($text as $line) {
if ($line == 'ABC04') {
echo $previous." - ".$line;
echo '<br>';
}
else{
echo $line;echo '<br>';
}
$previous = $line;
}
result is
ABC01
ABC02
ABC03
ABC03 - ABC04
ABC05
ABC06
but ABC03 on 3rd line
i want this result
ABC01
ABC02
ABC03 - ABC04
ABC05
ABC06
Maybe this is a solution?
I use array_search to find the value key.
The I add the value to the previous value.
Then I unset the found key and implode the array.
$text = "ABC01
ABC02
ABC03
ABC04
ABC05
ABC06";
$text = explode("\n",str_replace("\r", "", $text));
$text = array_filter($text, 'trim');
$key = array_search("ABC04", $text);
$text[$key-1] .= " - " . $text[$key];
Unset($text[$key]);
Echo implode("<br>\n", $text);
https://3v4l.org/WrTCZ
Edit; I see that indenting the code caused a problem at 3v4l.
Replaced the link to not indented
This one works too. It is simple
foreach ($text as $line) {
if ($line == 'ABC03') {
echo $line.' - ';
} else {
echo $line.'<br>';
}
}
Here is a foreach that works. But I am uncclear about what you really is trying to do.
foreach ($text as $line) {
if ($line == 'ABC03') {
echo $line.' - ';
}
else{
echo $line;
echo '<br>';
}
if ($line != 'ABC04')
$previous = $line;
}
}

str_replace when matched and followed by space or special characters

I have a working function that strips profanity words.
The word list is compose of 1700 bad words.
My problem is that it censored
'badwords '
but not
'badwords.' , 'badwords' and the like.
If I chose to remove space after
$badword[$key] = $word;
instead of
$badword[$key] = $word." ";
then I would have a bigger problem because if the bad word is CON then it will stripped a word CONSTANT
My question is, how can i strip a WORD followed by special characters except space?
badword. badword# badword,
.
function badWordFilter($data)
{
$wordlist = file_get_contents("badwordsnew.txt");
$words = explode(",", $wordlist);
$badword = array();
$replacementword = array();
foreach ($words as $key => $word)
{
$badword[$key] = $word." ";
$replacementword[$key] = addStars($word);
}
return str_ireplace($badword,$replacementword,$data);
}
function addStars($word)
{
$length = strlen($word);
return "*" . substr($word, 1, 1) . str_repeat("*", $length - 2)." " ;
}
Assuming that $data is a text that needs to be censored, badWordFilter() will return the text with bad words as *.
function badWordFilter($data)
{
$wordlist = file_get_contents("badwordsnew.txt");
$words = explode(",", $wordlist);
$specialCharacters = ["!","#","#","$","%","^","&","*","(",")","_","+",".",",",""];
$dataList = explode(" ", $data);
$output = "";
foreach ($dataList as $check)
{
$temp = $check;
$doesContain = contains($check, $words);
if($doesContain != false){
foreach($specialCharacters as $character){
if($check == $doesContain . $character || $check == $character . $doesContain ){
$temp = addStars($doesContain);
}
}
}
$output .= $temp . " ";
}
return $output;
}
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return $a;
}
return false;
}
function addStars($word)
{
$length = strlen($word);
return "*" . substr($word, 1, 1) . str_repeat("*", $length - 2)." " ;
}
Sandbox
I was able to answer my own question with the help of #maxchehab answer, but I can't declared his answer because it has fault at some area. I am posting this answer so others can use this code when they need a BAD WORD FILTER.
function badWordFinder($data)
{
$data = " " . $data . " "; //adding white space at the beginning and end of $data will help stripped bad words located at the begging and/or end.
$badwordlist = "bad,words,here,comma separated,no space before and after the word(s),multiple word is allowed"; //file_get_contents("badwordsnew.txt"); //
$badwords = explode(",", $badwordlist);
$capturedBadwords = array();
foreach ($badwords as $bad)
{
if(stripos($data, $bad))
{
array_push($capturedBadwords, $bad);
}
}
return badWordFilter($data, $capturedBadwords);
}
function badWordFilter($data, array $capturedBadwords)
{
$specialCharacters = ["!","#","#","$","%","^","&","*","(",")","_","+",".",","," "];
foreach ($specialCharacters as $endingAt)
{
foreach ($capturedBadwords as $bad)
{
$data = str_ireplace($bad.$endingAt, addStars($bad), $data);
}
}
return trim($data);
}
function addStars($bad)
{
$length = strlen($bad);
return "*" . substr($bad, 1, 1) . str_repeat("*", $length - 2)." ";
}
$str = 'i am bad words but i cant post it here because it is not allowed by the website some bad words# here with bad. ending in specia character but my code is badly strong so i can captured and striped those bad words.';
echo "$str<br><br>";
echo badWordFinder($str);

Change case of every nth letter in a string in PHP

Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
I am trying to write a simple program which takes every 4th letter (not character) in a string (not counting spaces) and changes the case to it's opposite (If it's in lower, change it to upper or vice versa).
What I have so far:
echo preg_replace_callback('/.{5}/', function ($matches){
return ucfirst($matches[0]);
}, $strInput);
Expected Result: "The sky is blue" should output "The Sky iS bluE"
$str = 'The sky is blue';
$strArrWithSpace = str_split ($str);
$strWithoutSpace = str_replace(" ", "", $str);
$strArrWithoutSpace = str_split ($strWithoutSpace);
$updatedStringWithoutSpace = '';
$blankPositions = array();
$j = 0;
foreach ($strArrWithSpace as $key => $char) {
if (empty(trim($char))) {
$blankPositions[] = $key - $j;
$j++;
}
}
foreach ($strArrWithoutSpace as $key => $char) {
if (($key +1) % 4 === 0) {
$updatedStringWithoutSpace .= strtoupper($char);
} else {
$updatedStringWithoutSpace .= $char;
}
}
$arrWithoutSpace = str_split($updatedStringWithoutSpace);
$finalString = '';
foreach ($arrWithoutSpace as $key => $char) {
if (in_array($key, $blankPositions)) {
$finalString .= ' ' . $char;
} else {
$finalString .= $char;
}
}
echo $finalString;
Try this:
$newStr = '';
foreach(str_split($str) as $index => $char) {
$newStr .= ($index % 2) ? strtolower($char) : strtoupper($char);
}
it capitalize every 2nd character of string
<?php
$str = "The sky is blue";
$str = str_split($str);
$nth = 4; // the nth letter you want to replace
$cnt = 0;
for ($i = 0; $i < count($str); $i++) {
if($str[$i]!=" " && $cnt!=$nth)
$cnt++;
if($cnt==$nth)
{
$cnt=0;
$str[$i] = ctype_upper($str[$i])?strtolower($str[$i]):strtoupper($str[$i]);
}
}
echo implode($str);
?>
This code satisfies all of your conditions.
Edit:
I would have used
$str = str_replace(" ","",$str);
to ignore the whitespaces in the string. But as you want them in the output as it is, so had to apply the above logic.

PHP Word Replacer/Spinner extremely slow

This function is part of a system i have created that creates semi-unique content, however this function needs to run 350* 200 words and is taking an awfully long time (300 seconds+) i am wondering if there is any OBVIOUS slow downs in the code.
<?php
set_time_limit(0);
function spinthis($article)
{
//words to be replaced
$words = file_get_contents('words.txt', FILE_USE_INCLUDE_PATH);
$checker = "2";
//Explode each word of the article into $word
foreach (explode(" ", $article) as $word) {
$checker = "4";
$checker2 = "0";
if($word != '') {
if (strpos($words, $word) == true) {
//Explode each line of words.txt into $spinLine
foreach (explode("\n", $words) as $spinLine) {
//Explode each word from the chosen line
foreach (explode("|", trim($spinLine, '{}')) as $spinword) {
$stage2count = count(explode("|", $spinLine));
//if word matches grab the rest of the lines
if ($spinword == $word) {
$replaceWords = explode("|", trim($spinLine, '{}'));
shuffle($replaceWords);
//Add replacement word
$newword = str_replace('}','',$replaceWords[0]);
$newword = str_replace('}','',$newword);
$newword = lcfirst($newword);
$earticle = $earticle.' '.$newword;
$checker = "1";
break 2;
}else{
$checker2++;
if ($checker2 == $stage2count) {
$checker = "0";
break 1;
}
}
}
}
}else{
$checker = "0";
$checker2++;
}
}
//CHECK IF IT IS A WORD
if ($checker == '0'){
//Word not found
$earticle = $earticle . ' ' . $word;
}elseif($checker == '1'){
//Word found
//Do Nothing
}elseif($checker == '2'){
//First time
$earticle = $word;
}
}
return $earticle;
}
?>
the words.txt file contains lots of the following:
{address|Tackle|Handle|Target}
{add|Include|Incorporate|Increase|Put}
{adequate|Sufficient|Satisfactory|Ample}
{adjustment|Realignment|Adjusting|Modification|Change}
{adjust|Alter|Change|Modify|Regulate}
{administer|Give|Provide|Dispense|Render}
{administration|Management|Supervision|Government}
{administrator|Manager|Supervisor|Officer|Owner}
{admire|Appreciate|Enjoy|Respect|Adore}
{admission|Entrance|Entry|Programs|Everyone}
{admit|Acknowledge|Confess|Disclose|Declare}
{adolescent|Teenage}
{adoption|Ownership|Usage|Use}
{adopt|Follow|Embrace|Undertake}
{adult|Grownup|Grown-up|Person}
{advanced|Advanced level|High level|Higher level|Sophisticated}
{advance|Progress}
{advantage|Benefit|Edge|Gain}
{adventure|Journey|Experience|Venture|Voyage}
{advertising|Marketing|Promotion}
{advice|Guidance|Assistance}
{adviser|Agent|Advisor|Mechanic|Coordinator}
{advise|Recommend|Suggest|Guide|Encourage}
{advocate|Suggest|Supporter}
{ad|Advert|Advertisement|Advertising|Offer}
{aesthetic|Visual|Cosmetic|Artistic|Functional}
{affair|Event|Matter|Occasion}
{affect|Impact|Influence}
{afford|Manage}
{afraid|Scared|Frightened|Reluctant|Fearful}
{afternoon|Mid-day|Morning|Day|Evening}
{agency|Company|Organization|Firm|Bureau}
{agenda|Plan|Goal|Schedule|Intention}
{agent|Broker|Realtor|Adviser|Representative}
{age|Era}
{aggression|Hostility|Violence}
{aggressive|Intense|Hostile|Ambitious|Extreme}
{ago|Previously|Before}
{agreement|Contract|Arrangement|Settlement|Deal}
{agree|Concur|Consent|Acknowledge|Recognize}
{agricultural|Farming}
{agriculture|Farming}
{ahead|Forward|Onward}
{ah|Oh}
{aide|Assist|Help|Guide|Benefit}
{aid|Help|Support|Assist|Assistance}
{aim|Goal|Purpose|Intention}
{aircraft|Plane|Airplane}
{airline|Flight}
{airplane|Plane|Aircraft|Airline|Jet}
{air|Atmosphere|Oxygen}
{aisle|Section|Fence}
{alarm|Alert}
{album|Recording|Record|Lp|Cd}
{alcohol|Booze|Liquor}
{alien|Unfamiliar|Noncitizen|Nonresident|Strange}
{alike|Likewise|Equally}
{alive|Living|Well}
{allegation|Claims|Claim|Accusation}
{allegedly|Presumably|Apparently|Purportedly|Theoretically}
{alleged|So-called|Supposed|Claimed|Assumed}
{alley|Street}
{alliance|Connections|Coalition}
{allow|Permit|Enable|Let}

Categories