PHP convert Latin intro Greek characters - php

Is it possible to convert Latin char into Greek?
example:
$string = 'OMEGA';
result:
$string = 'ΩΜΕΓΑ';

If you were able to set the transliterations yourself then you could just use str_replace. Here is an example:
$english = array('A','B','C','D','E','F','G','H','I','J');
$greek = array('a','b','c','d','e','f','g','h','i','j');
echo str_replace($english, $greek, "HELLO");
So, in my example A is replaced with a, B with b, C with c and so on. Any letter after J in the alphabet will remain unchanged. You could adjust this so O becomes Ω and so on ...

Try this one, because only str_replace will not work with non utf-8 chars.
if (!function_exists('mb_str_replace')) {
function mb_str_replace($search, $replace, $subject, &$count = 0)
{
if (!is_array($subject)) {
$searches = is_array($search) ? array_values($search) : [$search];
$replacements = is_array($replace) ? array_values($replace) : [$replace];
$replacements = array_pad($replacements, count($searches), '');
foreach ($searches as $key => $search) {
$parts = mb_split(preg_quote($search), $subject);
$count += count($parts) - 1;
$subject = implode($replacements[$key], $parts);
}
} else {
foreach ($subject as $key => $value) {
$subject[$key] = mb_str_replace($search, $replace, $value, $count);
}
}
return $subject;
}
}

Related

PHP: How to sort the characters should be in the order of first occurrence

I have string to be separated between vowels and consonants make them lower and ignore white space. sort by character according to the order they came out.
example string :
Sample Case
my output is :
vowels : aeae
consonants : smplcs
my expectation output is :
vowels : aaee
consonants : ssmplc
function sortCharacter($chars){
$chars = strtolower($chars);
$chars = str_replace(' ','',$chars);
$chars2 = str_split($chars);
$vowels = ['a','e','i','o','u'];
$v=[];
$c=[];
for ($i=0; $i < count($chars2) ; $i++) {
if (in_array($chars2[$i], $vowels)) {
array_push($v, $chars2[$i]);
}else{
array_push($c, $chars2[$i]);
}
}
echo "Vowel Character : <br>" ;
echo implode("", $v)."<br>";
echo "Consonant Character : <br>" ;
echo implode("", $c);
}
$text = 'Sample Case';
$vowels = '';
foreach (array_count_values(str_split(preg_replace('/[bcdfghjklmnpqrstvwxyz ]/', '', strtolower($text)))) as $k => $v) {
$vowels .= str_repeat($k, $v);
}
$consonants = '';
foreach (array_count_values(str_split(preg_replace('/[aeiou ]/', '', strtolower($text)))) as $k => $v) {
$consonants .= str_repeat($k, $v);
}
print_r($vowels);
echo "\n";
print_r($consonants);
Output:
aaee
ssmplc

Extract Keywords from text php

I am trying to extract relative keywords from description input which use Wysiwyg, with multi language english/arabic… using the following function but its not doing the task I want. Have a look the function I am using:
function extractKeyWords($string) {
mb_internal_encoding('UTF-8');
$stopwords = array();
$string = preg_replace('/[\pP]/u', '', trim(preg_replace('/\s\s+/iu', '', mb_strtolower($string))));
$matchWords = array_filter(explode(' ',$string) , function ($item) use ($stopwords) { return !($item == '' || in_array($item, $stopwords)
|| mb_strlen($item) <= 2 || is_numeric($item));});
$wordCountArr = array_count_values($matchWords);
// <p><p>
arsort($wordCountArr);
return array_keys(array_slice($wordCountArr, 0, 10)); }
figured it out ! Thanks
function generateKeywords($str)
{
$min_word_length = 3;
$avoid = ['the','to','i','am','is','are','he','she','a','an','and','here','there','can','could','were','has','have','had','been','welcome','of','home',' ','“','words','into','this','there'];
$strip_arr = ["," ,"." ,";" ,":", "\"", "'", "“","”","(",")", "!","?"];
$str_clean = str_replace( $strip_arr, "", $str);
$str_arr = explode(' ', $str_clean);
$clean_arr = [];
foreach($str_arr as $word)
{
if(strlen($word) > $min_word_length)
{
$word = strtolower($word);
if(!in_array($word, $avoid)) {
$clean_arr[] = $word;
}
}
}
return implode(',', $clean_arr);
}
This one seems very nice and comprehensive https://www.beliefmedia.com.au/create-keywords
Just make sure to change this line
$string = preg_replace('/[^\p{L}0-9 ]/', ' ', $string);
to
$string = preg_replace('/[^\p{L}0-9 ]/u', ' ', $string);
To support other langages (e.g Arabic)
And also better to use mb_strlen
If the string is in html format you can add the
strip_tags($str);
Before
$min_word_length = 3;

strrchr with strtr or str_replace in PHP

I have searched a lot of sites and SO answers for replacing characters in strings, but I didn't find a solution.
I need to replace only the last used character 'é' of a string.
It should work for every string, also if the string only contains once character 'é'.
code
echo strtr (strrchr ( 'accélérer','é' ), array ('é' => 'è')); // output èrer
echo str_replace("é","è",strrchr ( 'accélérer','é' )); // output èrer
desired results
accélérer -> accélèrer
sécher-> sècher
Have created custom function. Might be useful:
<?php
$str = 'accélérer';
$output = replaceMultiByte($str, 'é', 'è');
echo "OUTPUT=".$output; // accélèrer
echo '<br/><br/>';
$str = 'sécher';
$output = replaceMultiByte($str, 'é', 'è');
echo "OUTPUT=".$output; // sècher
function replaceMultiByte($str, $replace, $replaceWith)
{
$exp = explode($replace, $str);
$i = 1;
$cnt = count($exp);
$format_str = '';
foreach($exp as $v)
{
if($i == 1)
{
$format_str = $v;
}
else if($i == $cnt)
{
$format_str .= $replaceWith . $v;
}
else
{
$format_str .= $replace . $v;
}
$i++;
}
return $format_str;
}
?>
You could do something like this:
$str = 'accélérer';
$pos = strrpos( $str, 'é' );
if( $pos !== FALSE ) $str[$pos] = 'è';
Mat's answer did not work on me, so I work on more and I found è is 2 btye in strlen and 1 byte in mb_strlen. So in order to work with substr_replace
$str = "accélérer";
$pos = mb_strrpos($str, "é", "UTF-8");
if ($pos !== false) {
$str = substr_replace($str, "è", $pos + 1, strlen("è") );
}
var_dump($str); // string(11) "accélèrer"

PHP how to find uppercase in array

I have an array with many words, but some senteces are in uppercase. For example:
THIS SENTENCE IS UPPERCASE
this sentece is in lowercase
And I want to split this two sentences by \r\n, but I cant find how to do it
Here is how I retrive this array:
$result_pk_info = array();
while ($row = odbc_fetch_array($sql_pk_info))
{
$opisanie = iconv("cp1257", "UTF-8", trim($row['opis']));
$id = iconv("cp1257", "UTF-8", trim($row['pacientid']));
$date = iconv("cp1257", "UTF-8", trim($row['data']));
$desc = explode('##$', $opisanie);
$all_info = "<tr><td>".$desc[1]."</td></tr>";
$result_pk_info[] = $all_info;
}
in $desc I have words array in which I want to search and split uppercase and lowercase.
So can anyone help me with it?
UPD the text which I have hase something like this structure:
SENTENCE IN UPPERCASE Sentece in lower case
This function is what you're looking for :
function split_upper_lower ($string)
{
$words = explode (' ', $string);
$i = 0;
foreach ($words as $word)
{
if (ctype_upper ($word))
$new_string_array[++$i]['type'] = 'UPPER';
else
$new_string_array[++$i]['type'] = 'LOWER';
$new_string_array[$i]['word'] = $word;
}
$new_string = '';
foreach ($new_string_array as $key => $new_word)
{
if (!isset ($current_mode))
{
if (ctype_upper ($new_word))
$current_mode = 'UPPER';
else
$current_mode = 'LOWER';
}
if ($new_word['type'] === $current_mode)
{
$new_string .= $new_word['word'];
if (isset ($new_string_array[$key + 1]))
$new_string .= ' ';
}
else
{
$new_string .= "\r\n" . $new_word['word'];
if (isset ($new_string_array[$key + 1]))
$new_string .= ' ';
if ($current_mode === 'UPPER') $current_mode = 'LOWER';
else $current_mode = 'UPPER';
}
}
return $new_string;
}
Tested it with br :
$string = 'HI how ARE you doing ?';
echo split_upper_lower ($string);
Output :
HI
how
ARE
you doing ?
Use preg_match: http://php.net/manual/en/function.preg-match.php
$string = 'THIS SENTENCE IS UPPERCASE';
$string2 = 'this sentece is in lowercase';
if(preg_match ( '/[A-Z ]$/' , $string))
{
echo 'uppercase';
}
else
{
echo 'lowercase';
}
Use this in your loop through $desc. Where $string is one element of an array containing one string.
/[A-Z ]$/ will match all uppercase with spaces. You can just upgrade your regexp to grab something else from strings.
If I understood your question you can do like this ...
$desc = array ("abcd","ABCD","bbb","B");
foreach($desc as $value) {
if(ctype_upper($value)) {
// character is upper
} else {
// character is lower
}
}
This can be done using preg_match_all(). Use the following code,
$result_pk_info = array();
while ($row = odbc_fetch_array($sql_pk_info))
{
$opisanie = iconv("cp1257", "UTF-8", trim($row['opis']));
$id = iconv("cp1257", "UTF-8", trim($row['pacientid']));
$date = iconv("cp1257", "UTF-8", trim($row['data']));
$desc = explode('##$', $opisanie);
//converting $desc array to string
$string = implode(" " , $desc);
//Upper case Matching
$upprCase = preg_match_all('/[A-Z]/', $string, $uprmatches, PREG_OFFSET_CAPTURE);
if($upprCase){
foreach ($uprmatches as $match)
{
foreach($match as $value)
//Iam a uppercase
print $UpperCase = $value[0];
}}
//Splitting with \r\n
print "\r\n";
//lower case matching
$lowrCase = preg_match_all('/[a-z]/', $string, $lowrmatches, PREG_OFFSET_CAPTURE);
if($lowrCase){
foreach ($lowrmatches as $match)
{
foreach($match as $value)
//Iam a lowercase
print $lowerCase = $value[0];
}}
}

preg_replace - replace certain character

i want : He had XXX to have had it. Or : He had had to have XXX it.
$string = "He had had to have had it.";
echo preg_replace('/had/', 'XXX', $string, 1);
output :
He XXX had to have had it.
in the case of, 'had' is replaced is the first.
I want to use the second and third. not reading from the right or left, what "preg_replace" can do it ?
$string = "He had had to have had it.";
$replace = 'XXX';
$counter = 0; // Initialise counter
$entry = 2; // The "found" occurrence to replace (starting from 1)
echo preg_replace_callback(
'/had/',
function ($matches) use ($replace, &$counter, $entry) {
return (++$counter == $entry) ? $replace : $matches[0];
},
$string
);
Try this:
<?php
function my_replace($srch, $replace, $subject, $skip=1){
$subject = explode($srch, $subject.' ', $skip+1);
$subject[$skip] = str_replace($srch, $replace, $subject[$skip]);
while (($tmp = array_pop($subject)) == '');
$subject[]=$tmp;
return implode($srch, $subject);
}
$test ="He had had to have had it.";;
echo my_replace('had', 'xxx', $test);
echo "<br />\n";
echo my_replace('had', 'xxx', $test, 2);
?>
Look at CodeFiddle
Probably not going to win any concours d'elegance with this, but very short:
$string = "He had had to have had it.";
echo strrev(preg_replace('/dah/', 'XXX', strrev($string), 1));
Try this
Solution
function generate_patterns($string, $find, $replace) {
// Make single statement
// Replace whitespace characters with a single space
$string = preg_replace('/\s+/', ' ', $string);
// Count no of patterns
$count = substr_count($string, $find);
// Array of result patterns
$solutionArray = array();
// Require for substr_replace
$findLength = strlen($find);
// Hold index for next replacement
$lastIndex = -1;
// Generate all patterns
for ( $i = 0; $i < $count ; $i++ ) {
// Find next word index
$lastIndex = strpos($string, $find, $lastIndex+1);
array_push( $solutionArray , substr_replace($string, $replace, $lastIndex, $findLength));
}
return $solutionArray;
}
$string = "He had had to have had it.";
$find = "had";
$replace = "yz";
$solutionArray = generate_patterns($string, $find, $replace);
print_r ($solutionArray);
Output :
Array
(
[0] => He yz had to have had it.
[1] => He had yz to have had it.
[2] => He had had to have yz it.
)
I manage this code try to optimize it.

Categories