php str replace регистронезависимый
Как сделать регистронезависимую замену?
Результат выполнения:
я я я я
Нужно, чтобы было:
Я Я я я
Как это реализовать? Как сохранить регистронезависимость в символах, которые заменяют исходный текст?
Adamos, Вы судите объем по примеру? В моем случае все это «не сосчитать» займет как минимум несколько миллионов строк.
Одно правило с буквой «J» + каждой гласной (и да, по-отдельности их нельзя было заменить) заняло 110 строк.
Правило из 5 букв займет около 10 000 строк. Представьте, что таких правил 1 000.
А теперь представьте 10 000 правил, на регистры каждого из которых по 10 000 строк.
Mazino, неудачный пример, т.к. одна буква использовалась.
Задача выглядит так, чтобы это работало с символами внутри слова.
‘deRe’ => ‘деРе’ (при этом нельзя решить это через односимвольную автозамену, поскольку r = ръ, de = дэ и т.д.)
Задача в том, чтобы сделать замену латинских символов на кириллические, с сохранением регистра.
При этом количество правил настолько большое, что это трудно реализовать, если прописывать каждый регистр.
Например, есть правила:
C = Ц
Ci = Чи
Cia = Чья
Ciaa = Чиа
Стоит ввести CiAa и все рушится. Таких правил тысяча. Одно 5-буквенное правило, чтобы прописать для него регистр займет около тысячи строк.
Некоторые правила можно упростить через замену по регулярному выражению, но и там есть проблема:
Если я применю это на текст:
Acia acia
То результат будет:
Окcia Окcia [оба с большой]
Вот и получается, что есть две проблемы:
1. Решить задачу простым способом через замену латинских символов на кириллические, с сохранением регистра при таком переносе похоже невозможно.
2. Решить задачу можно огромным количеством правил, но даже при попытках их сократить, даже регулярные выражения не помогают 🙂
str_replace
(PHP 4, PHP 5, PHP 7, PHP 8)
str_replace — Заменяет все вхождения строки поиска на строку замены
Описание
Список параметров
Если search или replace являются массивами, их элементы будут обработаны от первого к последнему.
Искомое значение, также известное как needle (иголка). Для множества искомых значений можно использовать массив.
Строка или массив, в котором производится поиск и замена, также известный как haystack (стог сена).
Если передан, то будет установлен в количество произведённых замен.
Возвращаемые значения
Эта функция возвращает строку или массив с заменёнными значениями.
Примеры
Пример #1 Примеры использования str_replace()
Пример #2 Примеры потенциальных трюков с str_replace()
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Замечание о порядке замены
Так как str_replace() осуществляет замену слева направо, то при использовании множественных замен она может заменить ранее вставленное значение на другое. Смотрите также примеры на этой странице.
Эта функция чувствительна к регистру. Используйте str_ireplace() для замены без учёта регистра.
Смотрите также
User Contributed Notes 34 notes
A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:
>
?>
This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.
Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.
If you want to remove all dashes but one from the string ‘-aaa—-b-c——d—e—f’ resulting in ‘-aaa-b-c-d-e-f’, you cannot use str_replace. Instead, use preg_replace:
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):
To make this work, use «strtr» instead:
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.
$string = ‘I like to eat an apple with my dog in my chevy’ ;
// Echo: I like to eat an orange with my cat in my ford
?>
Here is the function:
Be aware that if you use this for filtering & sanitizing some form of user input, or remove ALL instances of a string, there’s another gotcha to watch out for:
// Remove all double characters
$string=»1001011010″;
$string=str_replace(array(«11″,»00″),»»,$string);
// Output: «110010»
$string=» ml> Malicious code html> etc»;
$string=str_replace(array(» «,» «),»»,$string);
// Output: » Malicious code etc»
This is what happens when the search and replace arrays are different sizes:
To more clearly illustrate this, consider the following example:
The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.
This strips out horrible MS word characters.
Just keep fine tuning it until you get what you need, you’ll see ive commented some out which caused problems for me.
There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.
There is an «invisible» character after the †for the right side double smart quote that doesn’t seem to display here. It is chr(157).
[] = ‘“’ ; // left side double smart quote
$find [] = ‘‒ ; // right side double smart quote
$find [] = ‘‘’ ; // left side single smart quote
$find [] = ‘’’ ; // right side single smart quote
$find [] = ‘…’ ; // elipsis
$find [] = ‘—’ ; // em dash
$find [] = ‘–’ ; // en dash
$replace [] = ‘»‘ ;
$replace [] = ‘»‘ ;
$replace [] = «‘» ;
$replace [] = «‘» ;
$replace [] = «. » ;
$replace [] = «-» ;
$replace [] = «-» ;
nikolaz dot tang at hotmail dot com’s solution of using json_encode/decode is interesting, but a couple of issues to be aware of with it.
json_decode will return objects, where arrays are probably expected. This is easily remedied by adding 2nd parameter ‘true’ to json_decode.
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your «replacements» in reverse.
So instead of starting from «A» and ending with «E»:
Str_ireplace не работает с кирилицей в регистре в файле utf8
С латиницей работает, а с кирилицей в Большом регистре не работает, если файл в кодировке utf8
Работает если файл в кодировке ANSI.
Нужно массив перевести в другую кодировку?
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Оператор if не работает с кирилицей
Перебираю строку по символьно ищу пара символов, ну например _Т если буква Т на кирилице то.
Помощь в написании контрольных, курсовых и дипломных работ здесь.
Подскажите, как реализовать замену переменных в rtf-файле из utf8
Данные в БД сервера хранятся в utf8 при замене переменных в rtf-файле вместо русского текста.
Не работает UTF8
Подскажите в чем трабла? Не могу внести данные на русском языке в таблицу, при добавлении из файла.
Как сделать слова, буквы четным индексом будет в верхнем регистре, а с нечетными в нижнем регистре
Ввожу слова или текс в textBox вывожу на label, как измененную строку у которой каждая буква с.
Напишите функцию, которая возвращает строку strв нижнем регистре, но каждый третий знак в верхнем регистре
Задание 1 Напишите функцию, которая возвращает строку strв нижнем регистре, но каждый третий знак.
Перевод из Utf8 в Builder 2009 не работает
Вопрос в сабж. Как быть? Пробовал Utf8ToAnsi, UTF8Decode, UTF8ToString и ничего не работает. Что.
Функции для работы со строками
Для получения информации о более сложной обработке строк обратитесь к функциями Perl-совместимых регулярных выражений. Для работы с многобайтовыми кодировками посмотрите на функции по работе с многобайтовыми кодировками.
Содержание
User Contributed Notes 24 notes
In response to hackajar yahoo
No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11’s «Strings» article under the «String access and modification by character» heading.
I’m converting 30 year old code and needed a string TAB function:
//tab function similar to TAB used in old BASIC languages
//though some of them did not truncate if the string were
//longer than the requested position
function tab($instring=»»,$topos=0) <
if(strlen($instring)
I use these little doo-dads quite a bit. I just thought I’d share them and maybe save someone a little time. No biggy. 🙂
Just a note in regards to bloopletech a few posts down:
The word «and» should not be used when converting numbers to text. «And» (at least in US English) should only be used to indicate the decimal place.
Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
/*
* example
* accept only alphanum caracteres from the GET/POST parameters ‘a’
*/
to: james dot d dot baker at gmail dot com
PHP has a builtin function for doing what your function does,
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.
Any string can (usually) be thought of as being in one of these ‘modes’:
pure = what the user actually typed / what you want to see on the page /
what is actually stored in the DB
gpc = incoming GET, POST or COOKIE data
sql = escaped for passing safely to RDBMS via SQL (also, data from DB
queries and file reads if you have magic_quotes_runtime on—which
is rare)
html = safe for html display (htmlentities applied)
Always knowing what mode your string is in—using these methods to
convert between modes—will prevent SQL injection and cross-site scripting.
This class refers to its own namespace (so it can work in PHP 4—there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.
Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST[‘username’]);
*/
Example: Give me everything up to the fourth occurance of ‘/’.
//
// string strtrmvistl( string str, [int maxlen = 64],
// [bool right_justify = false],
// [string delimter = «
\n»])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to ‘spread’ a string over two lines.
//
I really searched for a function that would do this as I’ve seen it in other languages but I couldn’t find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.
?>
Example: Give me everything up to the fourth occurance of ‘/’.
The functions below:
Are correct, but flawed. You’d need to use the === operator instead:
Here’s an easier way to find nth.
I was looking for a function to find the common substring in 2 different strings. I tried both the mb_string_intersect and string_intersect functions listed here but didn’t work for me. I found the algorithm at http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function
Here’s a simpler «simplest» way to toggle through a set of 1..n colors for web backgrounds:
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.
(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)
/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/
?>
Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using
, and then you can use this function to only return text up to the N’th
.
You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().
= ‘Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.’ ;
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida
Guest
Функция поиска. Пользователь задает строку и через
. WHERE table1.field1 LIKE ‘%строка%’.
tony2001
TeaM PHPClub
Guest
Спасибо, помогло! Плохо документацию смотрел. Там даже готовый пример был.
Помогло-то помогло, но обнаружились новые грабли. Сделал (т.е. слизал и упростил) «сложнейшую» функцию:
Полагаю, проблемы регистра умножились на какие-то национальные настройки? Как бы это обойти при условии, что к настройкам сервера я доступа не имею?
440hz
php.ru
Guest
woodfairy
Новичок
выставить локаль правильную? 8)
Вы общаетесь на каком-то ином уровне или я не умею читать между строк? Я в замешательстве. Что значит выставить локаль правильную? Как это сделать?
440hz
php.ru
woodfairy
Новичок
Спасибо за ответ, я уже успела и по форуму посмотреть. Только непонятно, как узнать, какая локаль через функции php. Конкретно, мне нужно узнать, какая кодировка по умолчанию используется на сервере и в эту кодировку с помощью iconv кодировать.
Прошу прощения за лишние вопросы, нашла.
Я посмотрела, как через setlocal посмотреть значение локали. Правда, остается один нерешенный вопрос.
Если setlocal(LC_ALL, NULL) вернет мне Russian_Russia.1251, то я могу со стопроцентной точностью утверждать, что текстовый файл с кодировкой win-1252 отобразится в блокноте нормально?
А если результат
LC_COLLATE=German_Germany.65001;LC_CTYPE=Russian_Russia.1251;LC_MONETARY=German_Germany.65001;LC_NUMERIC=German_Germany.65001;LC_TIME=German_Germany.65001
Можно утверждать, что файл в utf-8 прочитается или все же нет?
А цифры всегда присутствуют в ответе, чтобы по ним можно было однозначно идентифицировать кодировку?
То есть меня интересует, как точно определить используемую кодировку, чтобы в ней сохранить текстовый файл.