Replace a number input to alphabetical string in Codeignitor 4 - php

I want to fetch input from view file and split that number into digits and replace each digit to a specific alphabet and then store it in database,
can anyone help me in this problem
$data = [
'product_id' => $productId,
'vendor_id' => $vendor_id,
'purchase_date' => $purchase_date,
'landing_price' => $landing_price,
'retail_price' => $retail_price,
'wholesale_price' => $wholesale_price,
'current_price' => $current_price,
'vendor_current_price' => $vendor_current_price,
'freight' => $freight
];
$numbers = str_split($wholesale_price);
$replaceNumbers = [
1 => 'S',
2 => 'H',
3 => 'O',
4 => 'N',
5 => 'E',
6 => 'L',
7 => 'A',
8 => 'P',
9 => 'U',
0 => 'R'
];
$replace = str_replace($numbers, $replaceNumbers, $numbers);
$JoinReplacedWord = join($replace);
var_dump($numbers, $replace, $JoinReplacedWord);
die;
but i am not getting the number replaced i am getting the array replaced to alphabet
result -
array(4) {
[0]=> string(1) "1"
[1]=> string(1) "4"
[2]=> string(1) "5"
[3]=> string(1) "0"
}
array(4) {
[0]=> string(1) "S"
[1]=> string(1) "H"
[2]=> string(1) "O"
[3]=> string(1) "N"
}
string(4) "SHON"

use array_replace instead str_replace
$wholesale_price = 98765;
$numbers = array_flip(str_split($wholesale_price));
$replaceNumbers = [
1 => 'S',
2 => 'H',
3 => 'O',
4 => 'N',
5 => 'E',
6 => 'L',
7 => 'A',
8 => 'P',
9 => 'U',
0 => 'R'
];
$replace = array_slice(array_replace($numbers, $replaceNumbers), 0, count($numbers));
$JoinReplacedWord = join($replace);
var_dump($JoinReplacedWord);
//you will see string(5) "UPALE"
die;
EDIT : bug fix for repeated digit example 88775
$wholesale_price = 88775;
$numbers = str_split($wholesale_price);
//remove array_flip, because array flip will cause array just use last index when number have repeated digit
$replaceNumbers = [
1 => 'S',
2 => 'H',
3 => 'O',
4 => 'N',
5 => 'E',
6 => 'L',
7 => 'A',
8 => 'P',
9 => 'U',
0 => 'R'
];
$string = "";
foreach($numbers as $val){
$string .= $replaceNumbers[$val];
}
var_dump($string);
//you will see string(5) "PPAAE"
die;

If you just define your $replaceNumbers array slightly different your code will work
$data = [
'product_id' => 1,
'vendor_id' => 2,
'purchase_date' => '2021-12-12',
'landing_price' => 123.45,
'retail_price' => 234.56,
'wholesale_price' => 12345678.90,
'current_price' => 456.78,
'vendor_current_price' => 567.89,
'freight' => 111.22
];
$replaceNumbers = ['R', 'S', 'H', 'O', 'N', 'E', 'L', 'A', 'P', 'U'];
$numbers = str_split($data['wholesale_price']);
$replace = str_replace($numbers, $replaceNumbers, $numbers);
$JoinReplacedWord = join($replace);
var_dump($numbers, $replace, $JoinReplacedWord);
RESULT
RSHONELAPU

I try to dig into this. According to your description, your code does exactly what you want it to do. It splits up $data['wholesale_price'] and has each character replaced as defined by $replaceNumbers. According to your output, your input number was '1450'.
Do you mean by "i am not getting the number replaced" that $data is not refreshed? Then simply add $data['wholesale_price'] = $JoinReplacedWord;.

Related

How to replace the letters of a sting to anther assigned value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Am trying to in-script a sentence that contain strings. what i want to achieve is replacing the letters of the stings with another assigned value.
exmaple:
Value: 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
Assign Value: z y x w v u t s r q p o n m l k j i h g f e d c b a
"a" assigned to "z" and "b" assigned to "y" respectively in a sentence each time the sentence is run on the script.
INPUT: how are you brother?
OUTPUT: sld ziv blf yilghvi?
I want to write this script in PHP please someone should point me in the right direction.
Snippet:
function change_text($text){
$replacement_map = array_merge(
array_combine( range('a','z'), range('z','a')),
array_combine( range('A','Z'), range('Z','A'))
);
$length = strlen($text);
for($i = 0;$i < $length; ++$i){
if(!isset($replacement_map[ $text[$i] ])) continue; // skip characters that don't require replacing
$text[$i] = $replacement_map[ $text[$i] ]; // replace current character with the desired one
}
return $text;
}
echo change_text("how are you brother?");
Demo: https://3v4l.org/D1j1c
Algorithm:
Above code works for both lowercase and uppercase letters.
We build a map(associative array) of an alphabetic character with it's required destination character which looks like below:
Map(associative array):
array (
'a' => 'z',
'b' => 'y',
'c' => 'x',
'd' => 'w',
'e' => 'v',
'f' => 'u',
'g' => 't',
'h' => 's',
'i' => 'r',
'j' => 'q',
'k' => 'p',
'l' => 'o',
'm' => 'n',
'n' => 'm',
'o' => 'l',
'p' => 'k',
'q' => 'j',
'r' => 'i',
's' => 'h',
't' => 'g',
'u' => 'f',
'v' => 'e',
'w' => 'd',
'x' => 'c',
'y' => 'b',
'z' => 'a',
'A' => 'Z',
'B' => 'Y',
'C' => 'X',
'D' => 'W',
'E' => 'V',
'F' => 'U',
'G' => 'T',
'H' => 'S',
'I' => 'R',
'J' => 'Q',
'K' => 'P',
'L' => 'O',
'M' => 'N',
'N' => 'M',
'O' => 'L',
'P' => 'K',
'Q' => 'J',
'R' => 'I',
'S' => 'H',
'T' => 'G',
'U' => 'F',
'V' => 'E',
'W' => 'D',
'X' => 'C',
'Y' => 'B',
'Z' => 'A',
)
Now, we just loop over $text character by character and check if the character is present in our map. If yes, we replace it with the new destination character, else leave it as is and return the result.
Cause str_replace has problem with array replace ordering. so you can use this function to do it:
function change_text($text){
$search = range('a','z');
$replace = range('z','a');
$result = '';
foreach (str_split($text) as $index => $char){
if($found = array_search($char,$search)){
$result .= $replace[$found];
}else{
$result .= $char;
}
}
return $result;
}
echo change_text("how are you brother?"); // result sld aiv blf yilgsvi?
demo

Custom array multidim values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I had a problem with my code. for example, I have an array like this :
[
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
]
I want to change my array to be like this:
[
['a' => 'f', 'b' => 'h', 'c' => 'j'],
['a' => 'g', 'b' => 'i', 'c' => 'k']
]
I need help to solve this. Thanks
I tested this on my local computer
<?php
$array = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$ultimate_array = array();
foreach($array as $key1 => $child_array)
{
foreach($child_array as $i => $key2)
{
if(empty($ultimate_array[$i])) $ultimate_array[$i] = array();
$ultimate_array[$i][$key1] = $key2;
}
}
print_r($ultimate_array);
?>
This is a simple demonstration:
<?php
$input = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$output = [];
foreach ($input as $key=>$entries) {
foreach ($entries as $entry) {
$output[$key][] = $entry;
}
}
var_dump($output);
Some would consider this variant more elegant:
<?php
$input = [
'a' => ['f', 'g'],
'b' => ['h', 'i'],
'c' => ['j', 'k']
];
$output = [];
array_walk($input, function($entries, $key) use (&$output) {
array_walk($entries, function($entry) use (&$output, $key) {
$output[$key][] = $entry;
});
});
var_dump($output);
The obvious output of both variants is:
array(3) {
["a"]=>
array(2) {
[0]=>
string(1) "f"
[1]=>
string(1) "g"
}
["b"]=>
array(2) {
[0]=>
string(1) "h"
[1]=>
string(1) "i"
}
["c"]=>
array(2) {
[0]=>
string(1) "j"
[1]=>
string(1) "k"
}
}

Store key & value in other array in php

How to take the keys and values ​​of a array after having positioned to a known key ?
My array :
[Bolivia] => a
[Brazil] => v
[Belgium] => d
[Cuba] => c
[Croatia] => x
[Finland] => j
[Germany] => m
[India] => n
[Japan] => w
Know key : [Croatia]
The search result :
[Finland] => j
[Germany] => m
[India] => n
[Japan] => w
I would solve it like this:
$known_key = 'Croatia';
$input = [....];
$result = [];
$passed = false;
foreach($input as $key => $value){
if($passed){
$result[$key] = $value;
}
if($key == $known_key){
$passed = true;
}
}
You can use array_slice to get it.
<?php
$array = array(
'Bolivia' => 'a',
'Brazil' => 'v',
'Belgium' => 'd',
'Cuba' => 'c',
'Croatia' => 'x',
'Finland' => 'j',
'Germany' => 'm',
'India' => 'n',
'Japan' => 'w');
$keys = array_keys($array);
$keys_flip = array_flip($keys);
var_dump(array_slice($array, $keys_flip['Croatia'] + 1));
output:
ei#localhost:~$ php test.php
array(4) {
["Finland"]=>
string(1) "j"
["Germany"]=>
string(1) "m"
["India"]=>
string(1) "n"
["Japan"]=>
string(1) "w"
}

Multidimensional associative unique

I have 2x multidimensional array's as show below:
$x = [
0=>[
'a',
'b'
],
1=>[
'c',
'd'
],
2=>[
'e',
'f'
]
];
$y = [
0=>[
'b',
'a'
],
1=>[
'g',
'h'
],
2=>[
'i',
'j'
]
];
I would like to merge the 2x array's (x and y) with an output like this
$xy = [
0=>[
'c',
'd'
],
1=>[
'e',
'f'
],
2=>[
'g',
'h'
],
3=>[
'i',
'j'
]
];
As you can see, $x[0] is equal to a,b and $y[0] equal to b,a and they are duplicated. I would like to know if it's possible for a,b as same as b,a , I don't know how to get my code to look like this. I want to eliminate my duplicated array (a,b != b,a). Any duplication are not allowed, is that possible?
This should give you exactly what you've requested. I've used multiple foreach() loops to test if the value is firstly part of the $Y array, if so then remove from both arrays using unset(). I've then merged the two arrays together, removed the empty array dimensions and reset the key count.
$x = [0=>['a','b'],1=>['c','d'],2=>['e','f']];
$y = [ 0=>['b','a'],1=>['g','h'],2=>['i','j']];
foreach ($x as $key=>$value) {
foreach($x[$key] as $k=>$v) {
$search = array_search($v, $y[$key], true); //Find if value is equal to value in Y using a search
if ($search !== false) { //If so then remove value
unset($y[$key][$search]); //Remove from Array Y
unset($x[$key][$search]); //Remove from Array X
}
}
}
$newArray = array_merge($x, $y); //Merge two arrays together
foreach($newArray as $key => $value) { //Remove empty dimensions from Array
if (count($newArray[$key]) <= 0) {
unset($newArray[$key]);
}
}
$newArray = array_values($newArray); //Re-Number Keys so there in order
var_dump($newArray); //Array Output
Output
{
[0] => array(2) {
[0] => string(1)
"c" [1] => string(1)
"d"
}[1] => array(2) {
[0] => string(1)
"e" [1] => string(1)
"f"
}[2] => array(2) {
[0] => string(1)
"g" [1] => string(1)
"h"
}[3] => array(2) {
[0] => string(1)
"i" [1] => string(1)
"j"
}
}
Edit
Added unset() to remove value from both arrays as it's mentions that you would NOT like to have duplicate data from either array shown in new array.

Use Arabic Characters as Slug in Laravel

I am using this package Github : eluquent-sluggable-persian to use arabic language for slug, they use regular expression for the package Config File, I am not that good at it , the error i have is
ErrorException in sluggable.php line 106:
preg_replace(): Compilation failed: nothing to repeat at offset 0
sluggable.php is the config file that i should replace with the original config file, I need to know how to fix that.
The Code with the error
'method' => function($string, $separator = '-')
{
$_transliteration = array(
'/ä|æ|ǽ/' => 'ae',
'/ö|œ/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/ç|ć|ĉ|ċ|č/' => 'c',
'/Ð|Ď|Đ/' => 'D',
'/ð|ď|đ/' => 'd',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e',
'/Ĝ|Ğ|Ġ|Ģ/' => 'G',
'/ĝ|ğ|ġ|ģ/' => 'g',
'/Ĥ|Ħ/' => 'H',
'/ĥ|ħ/' => 'h',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i',
'/Ĵ/' => 'J',
'/ĵ/' => 'j',
'/Ķ/' => 'K',
'/ķ/' => 'k',
'/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L',
'/ĺ|ļ|ľ|ŀ|ł/' => 'l',
'/Ñ|Ń|Ņ|Ň/' => 'N',
'/ñ|ń|ņ|ň|ʼn/' => 'n',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o',
'/Ŕ|Ŗ|Ř/' => 'R',
'/ŕ|ŗ|ř/' => 'r',
'/Ś|Ŝ|Ş|Ș|Š/' => 'S',
'/ś|ŝ|ş|ș|š|ſ/' => 's',
'/Ţ|Ț|Ť|Ŧ/' => 'T',
'/ţ|ț|ť|ŧ/' => 't',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u',
'/Ý|Ÿ|Ŷ/' => 'Y',
'/ý|ÿ|ŷ/' => 'y',
'/Ŵ/' => 'W',
'/ŵ/' => 'w',
'/Ź|Ż|Ž/' => 'Z',
'/ź|ż|ž/' => 'z',
'/Æ|Ǽ/' => 'AE',
'/ß/' => 'ss',
'/IJ/' => 'IJ',
'/ij/' => 'ij',
'/Œ/' => 'OE',
'/ƒ/' => 'f'
);
$quotedReplacement = preg_quote($separator, '/');
$merge = array(
'/[^\s\p{Zs}\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]/mu' => ' ',
'/[\s\p{Zs}]+/mu' => $separator,
sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
);
$map = $_transliteration + $merge;
unset($_transliteration);
return preg_replace(array_keys($map), array_values($map), $string);
}
I have Fixed The Problem , Have Replace this method with another
'method' => function ($string, $separator = '-') {
if (is_null($string)) {
return "";
}
// Remove spaces from the beginning and from the end of the string
$string = trim($string);
// Lower case everything
// using mb_strtolower() function is important for non-Latin UTF-8 string | more info: https://www.php.net/manual/en/function.mb-strtolower.php
$string = mb_strtolower($string, "UTF-8");;
// Make alphanumeric (removes all other characters)
// this makes the string safe especially when used as a part of a URL
// this keeps latin characters and arabic charactrs as well
$string = preg_replace("/[^a-z0-9_\s\-ءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);
// Remove multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
// Convert whitespaces and underscore to the given separator
$string = preg_replace("/[\s_]/", $separator, $string);
return $string;
},
its Working now Thanks ^^
if You Want url arabic like This domain.com/category/معدات-وادوات
private function my_slug($string, $separator = '-')
{
$string = trim($string);
$string = mb_strtolower($string, 'UTF-8');
// Remove multiple dashes or whitespaces or underscores
$string = preg_replace("/[\s-_]+/", ' ', $string) ;
// Convert whitespaces and underscore to the given separator
$string = preg_replace("/[\s_]/", $separator, $string);
return rawurldecode($string);
}

Categories