str_replace exact match only - php

Good Day,
I am trying to create a morse code to text and text to morse code converter.
My code:
$letter = str_split(strtolower($_POST['text']));
$morse = $_POST['morse'];
$morsecmp = explode(" ",$morse);
$letter = implode(" ",$letter);
$mode = $_POST['sub'];
$morsecode = array(".-","-...","-.-.","-..","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",
".--.","--.-",".-.","...","-.","..-","...-",".--","-..-","-.--","--..",".");
$letters = array("a","b","c","d","f","g","h","i","j","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z","e");
if($mode == "Text to Morse Code"){
$letter = str_replace($letters,$morsecode,$letter);
$translated = $letter;
}else{
for($x=0;$x<sizeof($letters);$x++){
for($y=0;$y<sizeof($morsecmp);$y++){
if($morsecode[$x] === $morsecmp[$y]){
echo $morsecode[$x]." === ".$letters[$x]."<br>";
$morse = str_replace($morsecode[$x],$letters[$x],$morse);
}
}
}
$translated = $morse;
}
sample input:
.... . .-.. .-.. --- .-- --- .-. .-.. -..
sample output:
h e ed ed o w o r ed d
expected output:
hello wolrd
My problem is that when converting from morse code to text some characters are not captured properly due to str_replace limit where it will replace all string that is similar to the needle, so if i have to replace all "." to e it will also change "...." which should be actually an h.
any help on this would be greatly appreciated.
Thank You.

Just when you repalce the characters add an extra space for the search string.
$morse = $_POST['morse']." "; // this is to add an extra space at the end of the morse string.
Now we replace all occurrences of morse code strings followed by space with the desired letter.
$morse = str_replace($morsecode[$x]." ",$letters[$x],$morse);

First off, you don't have the full alphabet stored in your array. I noticed you're missing 'e'.
Blow the morse code into an array with explode(' ', $morse_code) and then do a replace on the array (use '/' to delimit words).
Condense it back to a string with implode().
heres an array for you to use, its got the whole alphabet (you can use array_flip to switch the keys and values for translating back and forth)
$translator_table = array(
'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' => '--.',
'0' => '-----',
'1' => '.----',
'2' => '..---',
'3' => '...--',
'4' => '....-',
'5' => '.....',
'6' => '-....',
'7' => '--...',
'8' => '---..',
'9' => '----.',
'.' => '.-.-.-',
',' => '--..--',
'?' => '..--.',
);

The only way to replace exact matches is:
$morse = preg_replace("#{$morsecode[$x]}#", $letters[$x], $morse, 1); //Limit to 1

Related

php display random value from key on array

I have array which have in letter format key.
'A' => array('WORD1','WORD2','WORD3'),
'B' => array('WORD1','WORD2','WORD3'),
'C' => array('WORD1','WORD2','WORD3'),
'D' => array('WORD1','WORD2','WORD3'),
'E' => array('WORD1','WORD2','WORD3'),
'F' => array('WORD1','WORD2','WORD3'),
'H' => array('WORD1','WORD2','WORD3'),
'G' => array('WORD1','WORD2','WORD3'),
...
I need to pick random value from each element. Example, when I set $output = "FGH"
Output will be:
F - (RANDOM WORD FROM ARRAY KEY F)\n
G - (RANDOM WORD FROM ARRAY KEY F)\n
H - (RANDOM WORD FROM ARRAY KEY H)\n
I used my code below but doesn't work..
$result = array();
foreach($chars as $char){
$random_key = array_rand($words[$char]); // get random key
$key = $words[$char][$random_key]; // get the word
unset($words[$char][$random_key]); // unset it so that it will never be repeated
$result[$key] = $char; // push it inside
}
Thanks to anyone that would help me
This gives a random word from whichever keys are specified in $output (note I have modified your $chars array slightly to make it obvious which value is being returned):
$chars = array(
'A' => array('A_WORD1','A_WORD2','A_WORD3'),
'B' => array('B_WORD1','B_WORD2','B_WORD3'),
'C' => array('C_WORD1','C_WORD2','C_WORD3'),
'D' => array('D_WORD1','D_WORD2','D_WORD3'),
'E' => array('E_WORD1','E_WORD2','E_WORD3'),
'F' => array('F_WORD1','F_WORD2','F_WORD3'),
'G' => array('G_WORD1','G_WORD2','G_WORD3'),
'H' => array('H_WORD1','H_WORD2','H_WORD3')
);
$output = 'FGH';
$result = array();
foreach(str_split($output) as $key) {
$result[] = $chars[$key][array_rand($chars[$key])];
}
var_dump($result);
The secret sauce here is the str_split() function.
<?php
$a=array("red","green","blue","yellow","brown");
$random_keys=array_rand($a,3);
echo $a[$random_keys[0]]."<br>";
echo $a[$random_keys[1]]."<br>";
echo $a[$random_keys[2]];
?>
for your reference : http://php.net/manual/en/function.array-rand.php
If you have already set up the random arrays to pick words from, it's quite straight forward with count() and rand().
//$globalWordArray = .......;
$selectedArray = array('B','D','F');
$wordList = array();
foreach($selectedArray as $words){
$wordList[] = $globalWordArray[$words][rand(0,count($globalWordArray[$words])-1];
}
This could be a solution:
$letters = array(
'A' => array('WORD1','WORD2','WORD3'),
'B' => array('WORD1','WORD2','WORD3'),
'C' => array('WORD1','WORD2','WORD3'),
'D' => array('WORD1','WORD2','WORD3'),
'E' => array('WORD1','WORD2','WORD3'),
'F' => array('WORD1','WORD2','WORD3'),
'H' => array('WORD1','WORD2','WORD3'),
'G' => array('WORD1','WORD2','WORD3'),
);
$output = "FGH";
for ($i=0; $i < strlen($output); $i++) {
echo $output[$i] ." - (RANDOM WORD FOR ARRAY KEY " . $output[$i]." ";
echo $letters[$output[$i]][array_rand($letters[$output[$i]])] .")" . "<br />";
}
Output is:
F - (RANDOM WORD FOR ARRAY KEY F WORD3)
G - (RANDOM WORD FOR ARRAY KEY G WORD3)
H - (RANDOM WORD FOR ARRAY KEY H WORD1)
Your logic looks wrong where you are actually performing the randomisation, see comments in your code below
$result = array();
foreach($chars as $char){
$random_key = array_rand($words[$char]);
$key = $words[$char][$random_key]; // This is a value at this point yet you named it key
unset($words[$char][$random_key]);
$result[$key] = $char; // This will create an entry in result such as $result['WORD 1'] = 'F', I'm sure thats wrong
}
Fixed version below
$result = array();
foreach($chars as $char){
$random_key = array_rand($words[$char]);
$value = $words[$char][$random_key];
unset($words[$char][$random_key]);
$result[$char] = $value;
}
What you have suggested you want is commonly referred to as a Shuffle Bag (http://kaioa.com/node/89). Shuffle Bags allow you to fill up collections with items and then pick them out randomly until the collection runs out of items. Think of it like the Bag of letters in Scrabble. There is a PHP implementation in the link above.
Using that sort of implementation would turn your foreach loop to this:
$result = array();
foreach($chars as $char){
$result[$char] = $words[$char]->next();
}

How to loop an array with strings as indexes in PHP

I had to make an array with as indexes A-Z (the alphabet). Each index had to have a value 0.
So i made this array:
$alfabet = array(
'A' => 0,
'B' => 0,
'C' => 0,
'D' => 0,
'E' => 0,
'F' => 0,
'G' => 0,
'H' => 0,
'I' => 0,
'J' => 0,
'K' => 0,
'L' => 0,
'M' => 0,
'N' => 0,
'O' => 0,
'P' => 0,
'Q' => 0,
'R' => 0,
'S' => 0,
'T' => 0,
'U' => 0,
'V' => 0,
'W' => 0,
'X' => 0,
'Y' => 0,
'Z' => 0
);
I also have got text from a file ($text = file_get_contents('tekst15.txt');)
I have putted the chars in that file to an array: $textChars = str_split ($text);
and sorted it from A-Z: sort($textChars);
What i want is that (with a for loop) when he finds an A in the textChars array, the value of the other array with index A, goes up by one (so like: $alfabet[A]++;
Can anyone help me with this loop? I have this atm:
for($i = 0; $i <= count($textChars); $i++){
while($textChars[$i] == $alfabet[A]){
$alfabet[A]++;
}
}
echo $alfabet[A];
Problem 1: i want to loop the alfabet array to, so now i only check for A but i want to check all indexes.
Problem2: this now returns 7 for each alphabet index i try so its totally wrong :)
I'm sorry about my english but thanks for your time.
Heard of the foreach loop?
foreach ($textChars as $index => $value) {
$alfabet[$value]++;
}
I assume that your $textChars array looks like
$textChars = array (
0 => 'A',
1 => 'A',
2 => 'B',
);
If so you can loop through it and use it's values to check if given index exists in $alfabet and then increment it.
foreach($textChars as $char){
if(isset($alfabet[$char])){
$alfabet[$char]++;
}
}
$fp = fopen('tekst15.txt', 'r');
if (!$fp) {
echo 'Could not open file tekst15.txt';
}
while (false !== ($char = fgetc($fp))) {
if(isset($alfabet[strtoupper($char)]))
{ $alfabet[strtoupper($char)] = $alfabet[strtoupper($char)]+1; }
}
The count_chars() function can give you that information immediately:
$stats = count_chars(file_get_contents('tekst15.txt'));
echo $stats['A']; // number of 'A' occurrences
echo $stats['O']; // number of 'O' occurrences
From your code:
while($textChars[$i] == $alfabet[A]){
$alfabet[A]++;
}
Made no sense at all; it compares each character from the text file to the value of $alfabet[A] which is 0 at first (not even a letter!).
The correct statement would be:
$alfabet[$textChars[$i]]++;

php break string into characters

In PHP is there any function to break up string in to characters or array.
Example: OVERFLOW
I need to break up the above text OVERFLOW int to: O V E R F L O W
OR
array(
0=> 'O',
1=> 'V',
2=> 'E',
3=> 'R',
4=> 'F',
5=> 'L',
6=> 'O',
7=> 'W'
)
or any otherway is there..?
There is a function for this: str_split
$broken = str_split("OVERFLOW", 1);
If your string can contain multi byte characters, use preg_split instead:
$broken = preg_split('##u', 'OVERFLOW', -1, PREG_SPLIT_NO_EMPTY);
use this function --- str_split();
This will split the string into character array.
Example:
$word="overflow";
$split_word=str_split($word);
Try like this....
$var = "OVERFLOW";
echo $var[0]; // Will print "O".
echo $var[1]; // Will print "V".
Use str_split
$str = "OVERFLOW" ;
$var = str_split($str, 1);
var_dump($var);
Output
array
0 => string 'O' (length=1)
1 => string 'V' (length=1)
2 => string 'E' (length=1)
3 => string 'R' (length=1)
4 => string 'F' (length=1)
5 => string 'L' (length=1)
6 => string 'O' (length=1)
7 => string 'W' (length=1)
Example
You could do:
$string = "your string";
$charArray = str_split($string);
Take a look at str_split
You can use it like this:
array str_split ( string $string [, int $split_length = 1 ] );
Tell you the truth, it already is broken up. So this would work:
$string = 'Hello I am the string.';
echo $string[0]; // 'H'
If you specifically want to split it, you could do this:
$string = 'Hello I am the string.';
$stringarr = str_split($string);
Depends if you really need to split it or not.

Make str_replace not replace a letter if follows another letter

I have a string which contains a math formula, like T + ST + s + t ...
I'm replacing all those letter identifiers with numbers using:
$ids = array(
'T' => $t1,
'ST', => $st,
's', => $s1,
't', => $t2,
'N', => 1,
);
foreach ($ids as $id => $value) {
if (strpos($formula, $id) !== false) {
$formula = str_replace($id, $value, $formula);
}
}
Which is ok in certain situations.
But if the formula has ST at the beginning I get a string like S345324 ..
I fixed this by moving ST in the first position in my array, but I feel it's not really the best option :)
Are there any other "nicer" solutions?
Are you looking for strtr()?
$ids = array(
'T' => $t1,
'ST' => $st,
's' => $s1,
't' => $t2,
'N' => 1,
);
$formula = strtr($formula, $ids);
Note that since strtr() always tries to find the longest possible match, it won't replace occurrences of ST with S$t1 (instead of $st), regardless of how your $replace_pairs array is ordered.
Example (as seen on codepad):
$ids = array(
'T' => 10,
'ST' => 20,
's' => 30,
't' => 40,
'N' => 1,
);
$formula = 'T + ST + s + t';
echo strtr($formula, $ids);
Prints:
10 + 20 + 30 + 40

How to remove accent from characters? (Leave only English alphabet glyphs)

I need to transform in PHP, a special character like ă -> a, â -> a, ț -> t and so on.
I need this especially for links, so any help would be appreciated.
When i want to get plain text (from utf-8) i'm using iconv.
iconv('utf8', 'ascii//TRANSLIT', $text);
If it's only for your url, urlencode may be a better idea.
Update the answer from Orlando, I add some more special char
function clean_special_chars ($s, $d=false) {
if($d) $s = utf8_decode( $s );
$chars = array(
'_' => '/`|´|\^|~|¨|ª|º|©|®/',
'a' => '/à|á|ả|ạ|ã|â|ầ|ấ|ẩ|ậ|ẫ|ă|ằ|ắ|ẳ|ặ|ẵ|ä|å|æ/',
'd' => '/đ/',
'e' => '/è|é|ẻ|ẹ|ẽ|ê|ề|ế|ể|ệ|ễ|ë/',
'i' => '/ì|í|ỉ|ị|ĩ|î|ï/',
'o' => '/ò|ó|ỏ|ọ|õ|ô|ồ|ố|ổ|ộ|ỗ|ö|ø/',
'u' => '/ù|ú|û|ũ|ü|ů|ủ|ụ|ư|ứ|ừ|ữ|ử|ự/',
'A' => '/À|Á|Ả|Ạ|Ã|Â|Ầ|Ấ|Ẩ|Ậ|Ẫ|Ă|Ằ|Ắ|Ẳ|Ặ|Ẵ|Ä|Å|Æ/',
'D' => '/Đ/',
'E' => '/È|É|Ẻ|Ẹ|Ẽ|Ê|Ề|Ế|Ể|Ệ|Ễ|Ê|Ë/',
'I' => '/Ì|Í|Ỉ|Ị|Ĩ|Î|Ï/',
'O' => '/Ò|Ó|Ỏ|Ọ|Õ|Ô|Ồ|Ố|Ổ|Ộ|Ỗ|Ö|Ø/',
'U' => '/Ù|Ú|Û|Ũ|Ü|Ů|Ủ|Ụ|Ư|Ứ|Ừ|Ữ|Ử|Ự/',
'c' => '/ć|ĉ|ç/',
'C' => '/Ć|Ĉ|Ç/',
'n' => '/ñ/',
'N' => '/Ñ/',
'y' => '/ý|ỳ|ỷ|ỵ|ỹ|ŷ|ÿ/',
'Y' => '/Ý|Ỳ|Ỷ|Ỵ|Ỹ|Ŷ|Ÿ/'
);
return preg_replace( $chars, array_keys( $chars ), $s );
}
You can use this:
function clean_special_chars( $s, $d=false )
{
if($d) $s = utf8_decode( $s );
$chars = array(
'_' => '/`|´|\^|~|¨|ª|º|©|®/',
'a' => '/à|á|â|ã|ä|å|æ/',
'e' => '/è|é|ê|ë/',
'i' => '/ì|í|î|ĩ|ï/',
'o' => '/ò|ó|ô|õ|ö|ø/',
'u' => '/ù|ú|û|ű|ü|ů/',
'A' => '/À|Á|Â|Ã|Ä|Å|Æ/',
'E' => '/È|É|Ê|Ë/',
'I' => '/Ì|Í|Î|Ĩ|Ï/',
'O' => '/Ò|Ó|Ô|Õ|Ö|Ø/',
'U' => '/Ù|Ú|Û|Ũ|Ü|Ů/',
'c' => '/ć|ĉ|ç/',
'C' => '/Ć|Ĉ|Ç/',
'n' => '/ñ/',
'N' => '/Ñ/',
'y' => '/ý|ŷ|ÿ/',
'Y' => '/Ý|Ŷ|Ÿ/'
);
return preg_replace( $chars, array_keys( $chars ), $s );
}

Categories