php Substitution Encoding Algorithm using cesar cipher - php

hello i am stack with this exercise as part of a test, how can i solve it or hint to solve it
/**
* Class SubstitutionEncodingAlgorithm
*/
class SubstitutionEncodingAlgorithm implements EncodingAlgorithm {
/**
* #var array
*/
private $substitutions;
/**
* SubstitutionEncodingAlgorithm constructor.
* #param $substitutions
*/
public function __construct(array $substitutions) {
$this->substitutions = array();
}
/**
* Encodes text by substituting character with another one provided in the pair.
* For example pair "ab" defines all "a" chars will be replaced with "b" and all "b" chars will be replaced with "a"
* Examples:
* substitutions = ["ab"], input = "aabbcc", output = "bbaacc"
* substitutions = ["ab", "cd"], input = "adam", output = "bcbm"
*
* #param string $text
* #return string
*/
public function encode($text) {
/**
* #todo: Implement it
*/
}
}
that what i ve tried so far in the encode () function but its not working, what i am doing wrong ?
public function encode($text) {
$length = strlen($text);
$newstr = '';
for ($i = 0; $i < $length; $i++) {
if (is_array($this->substitutions) && in_array(strtoupper($text[$i]), array_flip($this->substitutions)))
$newstr .= $this->substitutions[strtoupper($text[$i])];
}
return $newstr;
}
i understand that it is the cesar algorithm to be implemented so far, any help would be appreciated on how to do it

You could take the substitutions array and split it into two arrays, e.g.
$swapA = array();
$swapB = array();
//for each item in the substitutions array take the first char
// and place in swapA and the second/last char and place in swapB
foreach($substitutions as $sub)
{
$swapA = substr($sub,0,1);
$swapB = substr($sub,1,1);
}
// the str_replace will replace the all characters in $text chars
// from position x in swapA with chars in the same position in swapB
$output = str_replace($swapA, $swapB, $text);

$swapA = array();
$swapB = array();
$output = '';
$aText = str_split($text);
foreach($this->substitutions as $sub)
{
$swapA[] = substr($sub,0,1);
$swapB[] = substr($sub,1,1);
}
foreach ($aText as $letter) {
if (in_array(strtolower($letter, $swapA)) {
$positionOccurence = array_search ($letter, $swapA);
$replaced = $swapB[$positionOccurence];
$output .= str_replace($letter, $replaced, $letter);
} elseif (in_array(strtolower($letter), $swapB)) {
$positionOccurence = array_search ($letter, $swapB);
$replaced = $swapA[$positionOccurence];
$output .= str_replace($letter, $replaced, $letter);
} else {
$output .= $letter;
}
}
return $output;

My try - it is just for one byte per char text:
private function encodeText (string $text) : string {
$result = '';
for ($i = 0, $e = strlen ($text); $i < $e; $i ++) {
foreach ($this->substitutions as $substitution) {
$strpos = strpos ($substitution, $text {$i});
if ($strpos !== false) {
$result .= $strpos == 0 ? $substitution {1} : $substitution {0};
continue 2;
}
}
$result .= $text {$i};
}
return $result;
}
Other solution is much more faster and simpler:
first create in constructor array like:
foreach ($substitutions as $substitution) {
$this->substitutions ['from'] .= $substitution {0} . $substitution {1} . strtoupper($substitution {0} . $substitution {1});
$this->substitutions ['to'] .= $substitution {1} . $substitution {0} . strtoupper($substitution {1} . $substitution {0});
}
and then simply make translation:
public function encode($text)
{
return strtr ($text, $this->substitutions ['from'], $this->substitutions ['to']);
}

The problem is this:
public function __construct(array $substitutions) {
$this->substitutions = array();
}
It's an empty array.
Change to:
public function __construct(array $substitutions) {
$this->substitutions = $substitutions;
}
then test your logic.

Here is a more precise answer with edge cases in mind.
public function encode(string $text): string
{
$swapA = array();
$swapB = array();
$output = '';
$aText = str_split($text);
foreach ($this->substitutions as $sub) {
if (strlen($sub) == 2 && ($sub[0] != $sub[1])) {
$swapA[] = $sub[0];
$swapB[] = $sub[1];
} else {
throw new InvalidArgumentException ("Must have 2 different characters");
}
}
foreach ($aText as $letter) {
if (in_array(strtolower($letter), $swapA)) {
$positionOccurence = array_search($letter, $swapA);
if (strtolower($letter) != $letter) {
$replaced = strtoupper($swapB[$positionOccurence]);
} else {
$replaced = $swapB[$positionOccurence];
}
$output .= str_replace($letter, $replaced, $letter);
} elseif (in_array(strtolower($letter), $swapB)) {
$positionOccurence = array_search($letter, $swapB);
if (strtolower($letter) != $letter) {
$replaced = strtoupper($swapA[$positionOccurence]);
} else {
$replaced = $swapA[$positionOccurence];
}
$output .= str_replace($letter, $replaced, $letter);
} else {
$output .= $letter;
}
}
return $output;
}

Related

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);

Getting custom replace to work similar to how PHP PDO works

I just want to know how to replace a certain index character with an array constantly like how PDO works in PHP? Here is my code;
The the code
private $string;
public function __construct($string = null) {
if ($string !== null) {
$this->string = $string;
} else {
$this->string = '';
}
}
public function getString() {
return $this->string;
}
public function replaceWith($index, $array = array()) {
$lastArrayPoint = 0;
$i = 0;
while ($i < sizeof($this->string)) {
if (substr($this->string, $i, $i + 1) == $index) {
$newString[$i] = $array[$lastArrayPoint];
$i = $i . sizeof($array[$lastArrayPoint]);
$lastArrayPoint++;
} else {
$newString[$i] = $this->string[$i];
}
$i++;
}
return $this;
}
and the executing code
$string = new CustomString("if ? == true then do ?");
$string->replaceWith('?', array("mango", "print MANGO"));
echo '<li><pre>' . $string->getString() . '</pre></li>';
Thank you for the help I hope I will recieve.
$string = "if %s == true then do %s. Escaping %% is out of the box.";
$string = vsprintf($string, array("mango", "print MANGO"));
echo "<li><pre>$string</pre></li>";
str_replace has an optional count parameter, so you can make it replace one occurrance at a time. You can just loop through the array, and replace the next question mark for element N.
$string = "if %s == true then do %s";
$params = array("mango", "print MANGO");
foreach ($params as $param)
$string = str_replace('?', $param, $string, 1);
Thanks for the help guys but they did not work the way I wanted it to work. I have found a way to get it too work. Here is the code
public function replaceWith($index, $array = array()) {
$arrayPoint = 0;
$i = 0;
$newString = "";
while ($i < strlen($this->string)) {
if (substr($this->string, $i, 1) === $index) {
$newString .= $array[$arrayPoint];
$arrayPoint++;
} else {
$newString .= substr($this->string, $i, 1);
}
$i++;
}
$this->string = $newString;
return $this;
}
if anyone has a better way then you can tell me but for now this works.

Rewrite config parameter with phalcon

Is it possible to rewrite config parameter with phalcon?
I use ini File Type.
If not - tell me how to implement please.
if you want to create ini file with php, it is possible, even w/o phalcon.
from PHP docs comments:
Read file : $ini = INI::read('myfile.ini');
Write file : INI::write('myfile.ini', $ini);
custom INI class Features :
support [] syntax for arrays
support . in keys like bar.foo.something = value
true and false string are automatically converted in booleans
integers strings are automatically converted in integers
keys are sorted when writing
constants are replaced but they should be written in the ini file between braces : {MYCONSTANT}
class INI {
/**
* WRITE
*/
static function write($filename, $ini) {
$string = '';
foreach(array_keys($ini) as $key) {
$string .= '['.$key."]\n";
$string .= INI::write_get_string($ini[$key], '')."\n";
}
file_put_contents($filename, $string);
}
/**
* write get string
*/
static function write_get_string(& $ini, $prefix) {
$string = '';
ksort($ini);
foreach($ini as $key => $val) {
if (is_array($val)) {
$string .= INI::write_get_string($ini[$key], $prefix.$key.'.');
} else {
$string .= $prefix.$key.' = '.str_replace("\n", "\\\n", INI::set_value($val))."\n";
}
}
return $string;
}
/**
* manage keys
*/
static function set_value($val) {
if ($val === true) { return 'true'; }
else if ($val === false) { return 'false'; }
return $val;
}
/**
* READ
*/
static function read($filename) {
$ini = array();
$lines = file($filename);
$section = 'default';
$multi = '';
foreach($lines as $line) {
if (substr($line, 0, 1) !== ';') {
$line = str_replace("\r", "", str_replace("\n", "", $line));
if (preg_match('/^\[(.*)\]/', $line, $m)) {
$section = $m[1];
} else if ($multi === '' && preg_match('/^([a-z0-9_.\[\]-]+)\s*=\s*(.*)$/i', $line, $m)) {
$key = $m[1];
$val = $m[2];
if (substr($val, -1) !== "\\") {
$val = trim($val);
INI::manage_keys($ini[$section], $key, $val);
$multi = '';
} else {
$multi = substr($val, 0, -1)."\n";
}
} else if ($multi !== '') {
if (substr($line, -1) === "\\") {
$multi .= substr($line, 0, -1)."\n";
} else {
INI::manage_keys($ini[$section], $key, $multi.$line);
$multi = '';
}
}
}
}
$buf = get_defined_constants(true);
$consts = array();
foreach($buf['user'] as $key => $val) {
$consts['{'.$key.'}'] = $val;
}
array_walk_recursive($ini, array('INI', 'replace_consts'), $consts);
return $ini;
}
/**
* manage keys
*/
static function get_value($val) {
if (preg_match('/^-?[0-9]$/i', $val)) { return intval($val); }
else if (strtolower($val) === 'true') { return true; }
else if (strtolower($val) === 'false') { return false; }
else if (preg_match('/^"(.*)"$/i', $val, $m)) { return $m[1]; }
else if (preg_match('/^\'(.*)\'$/i', $val, $m)) { return $m[1]; }
return $val;
}
/**
* manage keys
*/
static function get_key($val) {
if (preg_match('/^[0-9]$/i', $val)) { return intval($val); }
return $val;
}
/**
* manage keys
*/
static function manage_keys(& $ini, $key, $val) {
if (preg_match('/^([a-z0-9_-]+)\.(.*)$/i', $key, $m)) {
INI::manage_keys($ini[$m[1]], $m[2], $val);
} else if (preg_match('/^([a-z0-9_-]+)\[(.*)\]$/i', $key, $m)) {
if ($m[2] !== '') {
$ini[$m[1]][INI::get_key($m[2])] = INI::get_value($val);
} else {
$ini[$m[1]][] = INI::get_value($val);
}
} else {
$ini[INI::get_key($key)] = INI::get_value($val);
}
}
/**
* replace utility
*/
static function replace_consts(& $item, $key, $consts) {
if (is_string($item)) {
$item = strtr($item, $consts);
}
}
}
find out more here: http://lt1.php.net/parse_ini_file

"like" search and highlighting in PHP

I have list of brands and want to provide a search function with highlighting. For example, there are the following brands
Apple
Cewe Color
L'Oréal
Microsoft
McDonald's
Tom Tailor
The user then types lor in search form. I'm using the following snippet for searching
class search {
private function simplify($str) {
return str_replace(array('&',' ',',','.','?','|','\'','"'), '', iconv('UTF-8', 'ASCII//TRANSLIT', $str));
}
public function do_search($search) {
$search = self::simplify($search);
$found = array();
foreach (self::$_brands as $brand) {
if (mb_strstr(self::simplify($brand['name']), $search) !== false) $found[]= $brand;
}
return $found;
}
}
That gives me:
Cewe Color
L'Oréal
Tom Tailor
How would be a highlighting possible? Like:
Cewe Co<b>lor</b>
L'<b>Oré</b>al
Tom Tai<b>lor</b>
Btw: I know, that most things can be done with str_replace(), but that fit my needs not in all cases
$highlighted = str_replace($search, "<b>$search</b>", $brand);
would be the simplest method.
:)
Works with FedEx also ;)
$_brands = array
(
"Apple",
"Cewe Color",
"L'Oréal",
"Microsoft",
"McDonald's",
"Tom Tailor"
);
$q = 'lor';
$search = clean($q);
foreach($_brands as $key => $brand){
$brand = clean($brand);
$x = stripos($brand, $search);
if($x !== false){
$regexp = NULL;
$l = strlen($q);
for($i = 0; $i < $l; $i++){
$regexp .= mb_strtoupper($q[$i]).'.?';
}
$regexp = substr($regexp, 0, strlen($regexp) - 2);
$new = $_brands[$key];
$new = preg_replace('#('.$regexp.')#ui', '<b>$0</b>', $new);
echo $new."<br />";
}
}
function clean($string){
$string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
$string = preg_replace('#[^\w]#ui', '', $string);
return $string;
}
self::$_brands contains result from database (containing columns name, name_lower, name_translit, name_simplified)
class search {
private function translit($str) {
return iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', str_replace(array('ä', 'ü', 'ö', 'ß'), array('a', 'u', 'o', 's'), mb_strtolower($str)));
}
private function simplify($str) {
return preg_replace('/([^a-z0-9])/ui', '', self::translit($str));
}
public function do_search($simplified) {
$found = array();
foreach (self::$_brands as $brand) {
if (mb_strstr($brand['name_simplified'], $simplified) !== false) $found[]= $brand;
}
return $found;
}
private function actionDefault() {
$search = $_POST['search_fld'];
$simplified = self::simplify($search);
$result = self::do_search($simplified);
$brands = array();
foreach ($result as $brand) {
$hl_start = mb_strpos($brand['name_simplified'], $simplified);
$hl_len = mb_strlen($simplified);
$brand_len = mb_strlen($brand['name']);
$tmp = '';
$cnt_extra = 0;
$start_tag = false;
$end_tag = false;
for ($i = 0; $i < $brand_len; $i++) {
if (($i - $cnt_extra) < mb_strlen($brand['name_simplified']) && mb_substr($brand['name_translit'], $i, 1) != mb_substr($brand['name_simplified'], $i - $cnt_extra, 1)) $cnt_extra++;
if (($i - $cnt_extra) == $hl_start && !$start_tag) {
$tmp .= '<b>';
$start_tag = true;
}
$tmp .= mb_substr($brand['name'], $i, 1);
if (($i - $cnt_extra + 1) == ($hl_start + $hl_len) && !$end_tag) {
$tmp .= '</b>';
$end_tag = true;
}
}
if ($start_tag && !$end_tag) $tmp .= '</b>';
$brands[] = "" . $tmp . "";
}
echo implode(' | ', $brands);
}
}

Optimizing Trie implementation

For no reason other than fun I implemented a Trie today. At the moment it supports add() and search(), remove() should also be implemented but I think that's fairly straight forward.
It is fully functional, but filling the Trie with data takes a little too much for my taste. I'm using this list as datasource: http://www.isc.ro/lists/twl06.zip (found somewhere else on SO). It takes ~11s to load. My initial implementation took ~15s so I already gave it a nice performance boost, but I'm still not satisfied :)
My question is: what else could give me a (substantial) performance boost? I'm not bound by this design, a complete overhaul is acceptable.
class Trie
{
private $trie;
public function __construct(TrieNode $trie = null)
{
if($trie !== null) $this->trie = $trie;
else $this->trie = new TrieNode();
$this->counter = 0;
}
public function add($value, $val = null)
{
$str = '';
$trie_ref = $this->trie;
foreach(str_split($value) as $char)
{
$str .= $char;
$trie_ref = $trie_ref->addNode($str);
}
$trie_ref->value = $val;
return true;
}
public function search($value, $only_words = false)
{
if($value === '') return $this->trie;
$trie_ref = $this->trie;
$str = '';
foreach(str_split($value) as $char)
{
$str .= $char;
if($trie_ref = $trie_ref->getNode($str))
{
if($str === $value) return ($only_words ? $this->extractWords($trie_ref) : new self($trie_ref));
continue;
}
return false;
}
return false;
}
public function extractWords(TrieNode $trie)
{
$res = array();
foreach($trie->getChildren() as $child)
{
if($child->value !== null) $res[] = $child->value;
if($child->hasChildren()) $res = array_merge($res, $this->extractWords($child));
}
return $res;
}
}
class TrieNode
{
public $value;
protected $children = array();
public function addNode($index)
{
if(isset($this->children[$index])) return $this->children[$index];
return $this->children[$index] = new self();
}
public function getNode($index)
{
return (isset($this->children[$index]) ? $this->children[$index] : false);
}
public function getChildren()
{
return $this->children;
}
public function hasChildren()
{
return count($this->children)>0;
}
}
Don't know php but,
in the following methods:
public function add($value, $val = null)
{
$str = '';
$trie_ref = $this->trie;
foreach(str_split($value) as $char)
{
$str .= $char;
$trie_ref = $trie_ref->addNode($str);
}
$trie_ref->value = $val;
return true;
}
public function search($value, $only_words = false)
{
if($value === '') return $this->trie;
$trie_ref = $this->trie;
$str = '';
foreach(str_split($value) as $char)
{
$str .= $char;
if($trie_ref = $trie_ref->getNode($str))
{
if($str === $value) return ($only_words ? $this->extractWords($trie_ref) : new self($trie_ref));
continue;
}
return false;
}
return false;
}
Why do you even need the $str .= $char (which I suppose is append)? This itself changes your O(n) time addition/searching to Omega(n^2) (n is length of $value) instead of O(n).
In a trie, you usually walk the trie while walking the string i.e you find the next node based on the current character, rather than the current prefix.
I suppose this implementation is for a Key|value type of insertion and lookup? Here is one that handles [English] words.
class Trie {
static function insert_word(Node $root, $text)
{
$v = $root;
foreach(str_split($text) as $char) {
$next = $v->children[$char];
if ($next === null)
{
$v->children[$char] = $next = new Node();
}
$v = $next;
}
$v->leaf = true;
}
static function get_words_sorted(Node $node, $text)
{
$res = array();
for($ch = 0; $ch < 128; $ch++) {
$child = $node->children[chr($ch)];
if ($child !== null)
{
$res = array_merge($res, Trie::get_words_sorted($child, $text . chr($ch)));
}
}
if ($node->leaf === true)
{
$res[] = $text;
}
return $res;
}
static function search(Node $root, $text)
{
$v = $root;
while($v !== null)
{
foreach(str_split($text) as $char) {
$next = $v->children[$char];
if ($next === null)
{
return false;
}
else
{
$v = $next;
}
}
if($v->leaf === true)
{
return true;
}
else
{
return false;
}
}
return false;
}
}
class Node {
public $children;
public $leaf;
function __construct()
{
$children = Array();
}
}
Example usage
$root = new Node();
$words = Array("an", "ant", "all", "allot", "alloy", "aloe", "are", "ate", "be");
for ($i = 0; $i < sizeof($words); $i++)
{
Trie::insert_word($root, $words[$i]);
}
$search_words = array("alloy", "ant", "bee", "aren't", "allot");
foreach($search_words as $word)
{
if(Trie::search($root, $word) === true)
{
echo $word . " IS in my dictionary<br/>";
}
else
{
echo $word . " is NOT in my dictionary <br/>";
}
}

Categories