phplibrary/src/Tools/String.php

107 lines
3.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
// from creole
function strToArray($str) {
$str = substr($str, 1, -1); // remove { }
$res = array();
$subarr = array();
$in_subarr = 0;
$toks = explode(',', $str);
foreach($toks as $tok) {
if ($in_subarr > 0) { // already in sub-array?
$subarr[$in_subarr][] = $tok;
if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component
$res[] = strToArray(implode(',', $subarr[$in_subarr]));
$in_subarr--;
}
} elseif ($tok{0} === '{') { // we're inside a new sub-array
if ('}' !== substr($tok, -1, 1)) {
$in_subarr++;
// if sub-array has more than one element
$subarr[$in_subarr] = array();
$subarr[$in_subarr][] = $tok;
} else {
$res[] = strToArray($tok);
}
} else { // not sub-array
$val = trim($tok, '"'); // remove " (surrounding strings)
// perform type castng here?
$res[] = $val;
}
}
return $res;
}
//Нормализация строк на русском
function normalizeRussian($str) {
$result = preg_replace('/\s+/',' ', $str);
if (is_string($result)) {
$result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям
$result = mb_strtolower($result);
$result = preg_replace('/ё/','е', $str); //е на ё
}
return $result;
}
//Проверка равенства двух строк на русском языке.
function equalRussianCheck($str1,$str2) {
return normalizeRussian($str1) == normalizeRussian($str2);
}
/**
* Попадает ли строка в список вариантов
* input: $str="foo1" $variants="foo1|foo2|foo3"
* output: true
* input: $str="foo" $variants="foo1|foo2|foo3"
* output: false
*/
function compare_string_to_variants($str, $variants){
$variants_array = explode('|', $variants);
$founded = false;
foreach ($variants_array as $variant) {
$founded = $founded || equalRussianCheck($variant, $str);
}
return $founded;
}
function mb_str_split($str) {
return preg_split('~~u', $str, null, PREG_SPLIT_NO_EMPTY);
}
function mb_strtr($str, $from, $to) {
return str_replace(mb_str_split($from), mb_str_split($to), $str);
}
function encodestring($st) {
$st = mb_strtr($st,"абвгдеёзийклмнопрстуфхъыэ !+-()", "abvgdeeziyklmnoprstufh_ie______");
$st = mb_strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE");
$st = strtr($st, array(
" " => '_',
"." => '_',
"," => '_',
"?" => '_',
"\"" => '_',
"'" => '_',
"/" => '_',
"\\" => '_',
"%" => '_',
"#" => '_',
"*" => '_',
"ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh",
"щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya",
"Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH",
"Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA",
"Й"=>"i", "й"=>"ie", "ё"=>"Ye",
""=>"N"
));
return strtolower($st);
}
function validate_encoded_string($st) {
$enc_st = encodestring($st);
return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st);
}