php ereg replace deprecated
I have written following PHP code:
After running above code, it gives following warning,
Deprecated: Function ereg_replace() is deprecated
How can I resolve this warning.
6 Answers 6
change the call to ereg_replace to use preg_replace instead
Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.
Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.
IIRC they suggest using the preg_ functions instead (in this case, preg_replace ).
Here is more information regarding replacing ereg_replace with preg_replace
Not the answer you’re looking for? Browse other questions tagged php deprecated ereg or ask your own question.
Linked
Related
Hot Network Questions
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Deprecated: Function ereg_replace() is deprecated
После перехода PHP с ветки PHP 5.2 (php52-5.2.17) на PHP 5.3 на части сайтов вылезли ошибки Deprecated: Function ereg_replace() is deprecated, хорошо что первоначальный переход я начал на тестовом сервере и было время подготовится, оценить размеры работ для корректного перехода уже на рабочем сервере.
И так, в ветки PHP 5.3 начали борьбу с некоторыми старыми функциями, для начала они выводят предупреждение и сообщают что функция уже не поддерживается и в будущем будет вообще удалена. Но в версии 5.3 еще можно избежать проблем включив режим поддержки старых функций
Это делается в разделе [mbstring]
; overload(replace) single byte functions by mbstring functions. ; mail(), ereg(), etc are overloaded by mb_send_mail(), mb_ereg(), ; etc. Possible values are 0,1,2,4 or combination of them. ; For example, 7 for overload everything. ; 0: No overload ; 1: Overload mail() function ; 2: Overload str*() functions ; 4: Overload ereg*() functions ; http://php.net/mbstring.func-overload ;mbstring.func_overload = 0 [mbstring] mbstring.func_overload = 7
Указав значение mbstring.func_overload равное 7 мы разрешаем все старые функции.
Но это решение можно использовать только как временное, хотя зачем оно вообще?
Ведь можно пока посидеть на ветке 5.2.
Более правильное решение — это замена в коде старых функций на новые, в случае использования ereg и eregi сделать это довольно просто.
было по-старому ereg(«language»,$uri) стало по-новому preg_match(«/language/»,$uri) если было eregi, то добавляем i после разделителя-слеша preg_match(«/language/i»,$uri)
Вот такими нехитрыми манипуляциями мы переходим на следующий уровень, уровень 5.3
Фразы: проблемы с PHP 5.3, после перехода на PHP 5.3, замена старых функций 5.2, замена ereg
ereg_replace
ereg_replace — Replace regular expression
Această funcție este ÎNVECHITĂ începând cu PHP 5.3.0 și ELIMINATĂ în PHP 7.0.0.
Variante alternative pentru această funcție sunt:
Descrierea
Parametri
A POSIX extended regular expression.
Valorile întoarse
Exemple
For example, the following code snippet prints «This was a test» three times:
Example #1 ereg_replace() example
One thing to take note of is that if you use an integer value as the replacement parameter, you may not get the results you expect. This is because ereg_replace() will interpret the number as the ordinal value of a character, and apply that. For instance:
Example #2 ereg_replace() example
Example #3 Replace URLs with links
A se vedea și
User Contributed Notes 23 notes
It’s worth mentioning for ultimate clarity that you’re safest using double quotes when matching a pattern, since without them, metacharacters will be interpreted as a backslash plus another character.
Granted, this is part of the language syntax for the string type, but it might not be quite so obvious when dealing with patterns in this function, which is taking the pattern as a parameter.
So if you find that ‘[\n]’ is taking the ‘n’ out of your string and leaving the new lines alone, switch to doubles before changing anything else.
If you want the function to process query strings, such as:
modify the function as follows:
Since ereg_replace is now deprecated, many users will be coming to this page, in an attempt to troubleshoot and fix broken scripts after a PHP upgrade.
ereg_replace is essentially a search and replace function and it follows a pattern like this:
Lets take a real world example.
If using the deprecated ereg_replace function, it might look something like this:
?>
But to avoid those deprecated errors, we change the function name to preg_replace and add a set of delimiters, in this case the 2 forward slashes / / where the contents inside that are matched as the ‘find this’ portion.
So to summarize: ereg_replace is a deprecated search and replace action where preg_replace can be used instead, and it follows a pattern as described earlier where it takes the input data, finds a match based on what you are looking for, replaces it with something else you define, and then gives you an output data variable that you can use in your script or page. Hopefully by understanding the process, the php code functions wont seem like voodoo and you could troubleshoot and fix many of the deprecated errors yourself.
Ошибка “Function ereg() или split() is deprecated in” как решить проблему?
Вы также получаете эту устаревшую ошибку при работе с Joomla 2.5 или 3.0? Не волнуйтесь, с вашей установкой Joomla ИЛИ шаблоном все в порядке, это можно исправить за считанные минуты.
Вы получите сообщение об устаревшей ошибке, если некоторые функции PHP, такие как split (), несовместимы с версией PHP.
Есть несколько способов исправить эти устаревшие ошибки, чтобы мы могли пройти через них одну за другой:
1. PHP 5.3 и более поздние версии больше не поддерживают функции split () и ereg (). поэтому вы можете просто понизить версию PHP до версии 5.2 ИЛИ меньше, и эта ошибка будет исправлена.
2. Другой вариант – изменить функцию. Вы можете заменить функцию split () функцией explode (), которая поддерживается в PHP 3 и более поздних версиях. Сделайте то же самое для функции ereg (). – Это очень рекомендуемый вариант.
3. Если вы не уверены ИЛИ не хотите вносить какие-либо изменения, указанные выше, вы можете просто скрыть эту ошибку, отключив отчет об ошибках в файле конфигурации Joomla.
Если же есть проблема не работающих функций в новой версии.
А именно таких функций: ereg(), eregi() и split(). После переноса наших сайтов на версию PHP 5.3 начали появляться ошибки типа: Function ereg() is deprecated in, Function eregi() is deprecated in или function split() is deprecated in.
Ошибку Function ereg_replace() is deprecated in можно пофиксить всего лишь заменив ereg_replace на preg_replace.
Аналогичным образом решается ошибка: deprecated: function set_magic_quotes_runtime() is deprecated in
Нужно сделать так к примеру:
@set_magic_quotes_runtime(0); заменить на ini_set(‘magic_quotes_runtime’, 0);
Также хотел бы обратить ваше внимание на то, что не стоит включать поддержку старых функций вместо того чтобы заменить их на новые, потому что в последующих релизах PHP вам все равно придется изменять их на новые, ведь все старые функции будут удалены полностью.
Оставляйте ваши отзывы или пишите ваши вопросы в комментарии, постараемся помочь если у вас возникнут трудности.
mb_ereg_replace
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
mb_ereg_replace — Осуществляет замену по регулярному выражению с поддержкой многобайтовых кодировок
Описание
Список параметров
Шаблон регулярного выражения.
В pattern могут использоваться многобайтовые символы.
Проверяемая строка ( string ).
Возвращаемые значения
Список изменений
Версия | Описание |
---|---|
8.0.0 | options теперь допускает значение null. |
7.1.0 | Функция проверяет, корректна ли string для текущей кодировки. |
7.1.0 | Модификатор e объявлен устаревшим. |
Примечания
Никогда не используйте модификатор e при работе с данными, полученными из недостоверных источников. Не выполняется никакого автоматического экранирования этих данных (в отличие от preg_replace() ). Игнорирование данных требований, скорее всего, создаст уязвимость выполнения удалённого кода в вашем приложении.
Смотрите также
User Contributed Notes 16 notes
Unlike preg_replace, mb_ereg_replace doesn’t use separators
I got a pretty nasty error while trying to parse table rows(all contents were set to UTF-8) from the database for a dictionary project. The idea was to get all the rows from the first table (that is a table with bulgarian phrase in the first field, and its translation in english, french and german in the next fields). I needed to index all the bulgarian words that are found in the table to make an intelligent search. And that is where my headache started.
First of all, even with mb_strtolower() a lot of cyrillic characters went corrupted (ex: ‘т,ъ,у,ф,б,г,з,ж,’ etc. ). After an hour of different attempts I got such a solution:
( «UTF-8» );
mb_regex_encoding ( «UTF-8» );
?>
To work properly I got to set all the internal encoding settings to UTF-8. Else the default Latin-1 got half my database with missing characters.
I am posting this solution just in case someone has encountered a similar problem. Hope it helps you in case you need something like that.