Php str replace callback

ktomk / str_ureplace.php

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

/**
* str_ureplace
*
* str_replace like function with callbacks for replacement(s).
*
* @param string|array $search
* @param callback|array $replace
* @param string|array $subject
* @param int $replace_count
* @return string|array subject with replaces, FALSE on error.
*/
function str_ureplace ( $ search , $ replace , $ subject , & $ replace_count = null )
$ replace_count = 0 ;
// validate input
$ search = array_values(( array ) $ search );
$ searchCount = count( $ search );
if (! $ searchCount )
return $ subject ;
>
foreach ( $ search as & $ v )
$ v = ( string ) $ v ;
>
unset( $ v );
$ replaceSingle = is_callable( $ replace );
$ replace = $ replaceSingle ? array ( $ replace ) : array_values(( array ) $ replace );
foreach ( $ replace as $ index => $ callback )
if (!is_callable( $ callback ))
throw new Exception (sprintf( ‘Unable to use %s (#%d) as a callback’ , gettype( $ callback ), $ index ));
>
>
// search and replace
$ subjectIsString = is_string( $ subject );
$ subject = ( array ) $ subject ;
foreach ( $ subject as & $ haystack )
if (!is_string( $ haystack )) continue ;
foreach ( $ search as $ key => $ needle )
if (! $ len = strlen( $ needle ))
continue ;
$ replaceSingle && $ key = 0 ;
$ pos = 0 ;
while ( false !== $ pos = strpos( $ haystack , $ needle , $ pos ))
$ replaceWith = isset( $ replace [ $ key ]) ? call_user_func( $ replace [ $ key ], $ needle , ++ $ replace_count ) : » ;
$ haystack = substr_replace( $ haystack , $ replaceWith , $ pos , $ len );
>
>
>
unset( $ haystack );
return $ subjectIsString ? reset( $ subject ) : $ subject ;
>

Источник

Замена с коллбэком через регулярки в PHP

Пусть нам нужно найти все конструкции вида число+число= и сделать так, чтобы после равно появился результат сложения.

Для решения подобной задачи удобно воспользоваться функцией preg_replace_callback , которая работает аналогично функции preg_replace — находит и заменяет по регулярному выражению, но позволяет выполнять дополнительные манипуляции с найденными кусочками.

Первым параметром функция принимает регулярку, вторым — на что меняем, третьим — строку, в которой осуществляется замена.

При этом во второй параметр следует передавать функцию-коллбэк, которая будет вызвана для каждого найденного совпадения.

Первым параметром коллбэка нужно указать переменную, в которую будет попадать найденное. Эта переменная будет представлять собой массив карманов найденного.

Давайте попробуем на практике. Напишем, код, который поймает наши подстроки, при этом положив первое число в первый карман, а второе — во второй:

В результате наш var_dump сработает три раза, по очереди выведя следующее:

Идем дальше. Каждое совпадение будет заменено на то, что возвращает коллбэк через return . Давайте для примера заменим каждую из искомых подстрок на знак ‘!’ :

А теперь заменим каждую подстроку на сумму пары чисел в ней:

Получается, что наша задача почти решена. Осталось сделать так, чтобы перед суммой чисел оставалась искомая подстрока. Для этого будем вставлять перед суммой содержимое нулевого кармана:

Дана строка с целыми числами. С помощью регулярки преобразуйте строку так, чтобы вместо этих чисел стояли их квадраты.

Источник

preg_replace_callback

Поведение этой функции во многом напоминает preg_replace() , за исключением того, что вместо параметра replacement необходимо указывать callback -функцию.

Список параметров

Искомый шаблон. Может быть как строкой, так и массивом строк.

Вызываемая callback-функция, которой будет передан массив совпавших элементов из строки subject . Callback-функция должна вернуть строку с заменой. Callback-функция должна быть описана так:

Достаточно часто callback функция, кроме как в вызове preg_replace_callback() , ни в чем больше не участвует. Исходя из этих соображений, можно использовать анонимные функции для создания callback-функции непосредственно в вызове preg_replace_callback() . Если вы используете такой подход, вся информация, связанная с заменой по регулярному выражению, будет собрана в одном месте, и пространство имен функций не будет загромождаться неиспользуемыми записями.

Пример #1 preg_replace_callback() и анонимная функция

/* фильтр, подобный тому, что используется в системах Unix
* для преобразования заглавных букв в началье параграфа в строчные */
$fp = fopen ( «php://stdin» , «r» ) or die( «не удалось прочесть stdin» );
while (! feof ( $fp )) $line = fgets ( $fp );
$line = preg_replace_callback (
‘|

\s*\w|’ ,
function ( $matches ) return strtolower ( $matches [ 0 ]);
>,
$line
);
echo $line ;
>
fclose ( $fp );
?>

Строка или массив строк для поиска и замены.

Максимально возможное количество замен для каждого шаблона в каждой строке subject . По умолчанию равно -1 (без ограничений).

Если указана, то эта переменная будет заполнена количеством произведенных замен.

Возвращаемые значения

preg_replace_callback() возвращает массив, если параметр subject является массивом, иначе возвращается строка. В случае ошибок возвращается NULL

Если найдены совпадения, будет возвращена результирующая строка, иначе subject вернется неизмененным.

Список изменений

Версия Описание
5.1.0 Добавлен параметр count

Примеры

Пример #2 Пример использования preg_replace_callback()

// Этот текст был использован в 2002 году
// мы хотим обновить даты к 2003 году
$text = «День дураков: 01/04/2002\n» ;
$text .= «Последнее Рождество было: 24/12/2001\n» ;
// callback-функция
function next_year ( $matches )
// как обычно: $matches[0] — полное вхождение шаблона
// $matches[1] — вхождение первой подмаски,
// заключенной в круглые скобки, и так далее.
return $matches [ 1 ].( $matches [ 2 ]+ 1 );
>
echo preg_replace_callback (
«|(\d/\d/)(\d)|» ,
«next_year» ,
$text );

Результат выполнения данного примера:

День дураков: 01/04/2003 Последнее Рождество было: 24/12/2002

Пример #3 Рекурсивная обработка BB-кодов с помощью preg_replace_callback()

$input = «верх [indent] глубже [indent] еще глубже [/indent] глубже [/indent] верх» ;

function parseTagsRecursive ( $input )

return preg_replace_callback ( $regex , ‘parseTagsRecursive’ , $input );
>

$output = parseTagsRecursive ( $input );

Смотрите также

  • «Регулярные выражения PCRE»
  • preg_quote() — Экранирует символы в регулярных выражениях
  • preg_replace() — Выполняет поиск и замену по регулярному выражению
  • preg_last_error() — Возвращает код ошибки выполнения последнего регулярного выражения PCRE
  • «Анонимные функции»
  • информация о типе callback

Источник

Search & Replace with Multiple Patterns and Callbacks

Learn how to use preg_replace_callback_array() and preg_replace_callback() functions to perform a regular expression search and replace using callbacks.

preg_replace_callback()

The preg_replace_callback() function takes six parameters:

  1. $pattern : The regular expression as a string or a string array to search for.
  2. $callback : The callback function, pass the function name as a string or use an anonymous function to declare the callback.
  3. $subject : The input string or array to search through.
  4. $limit (optional): The maximum possible replacements, default to -1 (no limit).
  5. &$count (optional): If specified, this variable will be filled with the number of replacements done.
  6. $flags (optional): A combination of the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags, see preg_match() tutorial for more details.

This function works the same as the preg_repalce() except that it takes the $callback function instead of the $replacement string.

The callback function will be called and passed an array of matched elements in the subject string. The first element of the array contains the whole matched text, and additional array elements contain any matched subpatterns. See the following example:

CB', $subject); function CB($m) < echo $m[0].'
'; # $100 - the complete match echo $m[1].'
'; # $ - first subpattern match echo $m[2].'
'; # 100 - second subpattern match >

You can change the matched text with your own algorithm and return the changed text as the replacement text. See the following example, we just created a currency conversion tool that converts the USD to EUR from the subject:

 echo $newStr; #Prints: Sum of €98 and €49 is €147

Instead of using a regular function as the callback you can use an anonymous function:

function ($m) , $subject, -1, $count ); echo $subject .'
'. $newStr .'
'; echo 'No. of changes: '.$count; /* Sum of $100 and $50 is $150 Sum of €98 and €49 is €147 No. of changes: 3 */

Since PHP 7.4, you can also use arrow function as it has a more concise syntax:

fn($m) => '€' . $m[2] * 0.98, $subject, -1, $count ); echo $subject .'
'. $newStr .'
'; echo 'No. of changes: '.$count; /* Sum of $100 and $50 is $150 Sum of €98 and €49 is €147 No. of changes: 3 */

preg_replace_callback_array()

The preg_replace_callback_array() function takes five parameters:

  1. $pattern : An associative array mapping patterns (keys) to callables (values).
  2. $subject : The input string or array to search through.
  3. $limit (optional): The maximum possible replacements, default to -1 (no limit).
  4. &$count (optional): If specified, this variable will be filled with the number of replacements done.
  5. $flags (optional): A combination of the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags, see preg_match() tutorial for more details.

The preg_replace_callback_array() function introduced in PHP 7. This function allows you to specify an array of patterns (regular expressions) as keys, with the value representing an independent callback function.

When a pattern (array key) matched, the corresponding callback function will be called and passed an array of matched elements in the subject string.

Similar to the preg_replace_callback() function the first element of the array contains the whole matched text, and additional array elements contain any matched subpatterns. In the following example, we created a separated pattern for each currency, and when the specific currency pattern matched, its value, a callback function, executes:

 Sum of ₹7957 and ₹3979 is ₹11936 
Sum of £82 and £41 is £123'; $pattern = ['/\$(7+)/' => 'usdToEur', '/\£(6+)/' => 'gbpToEur', '/\₹(4+)/' => 'inrToEur' ]; $newStr = preg_replace_callback_array($pattern, $subject); function usdToEur($m) < return '€'. $m[1] * 0.98; >function inrToEur($m) < return '€'. $m[1] * 0.012; >function gbpToEur($m) < return '€'. $m[1] * 1.19; >echo $newStr; /*Prints: Sum of €98 and €49 is €147 Sum of €95.484 and €47.748 is €143.232 Sum of €97.58 and €48.79 is €146.37*/

Example: Using anonymous functions with preg_replace_callback_array :

 Sum of ₹7957 and ₹3979 is ₹11936 
Sum of £82 and £41 is £123'; $pattern = [ '/\$(6+)/' => function ($m) , '/\£(8+)/' => function ($m) , '/\₹(1+)/' => function ($m) ]; $newStr = preg_replace_callback_array($pattern, $subject); echo $newStr; /*Prints: Sum of €98 and €49 is €147 Sum of €95.484 and €47.748 is €143.232 Sum of €97.58 and €48.79 is €146.37*/

Example: PHP 7.4 allows you to use arrow functions:

 Sum of ₹7957 and ₹3979 is ₹11936 
Sum of £82 and £41 is £123'; $pattern = [ '/\$(6+)/' => fn ($m) => '€'. $m[1] * 0.98, '/\£(7+)/' => fn ($m) => '€'. $m[1] * 1.19, '/\₹(1+)/' => fn ($m) => '€'. $m[1] * .012]; $newStr = preg_replace_callback_array($pattern, $subject); echo $newStr; /*Prints: Sum of €98 and €49 is €147 Sum of €95.484 and €47.748 is €143.232 Sum of €97.58 and €48.79 is €146.37*/

More Regular Expressions Tutorials:

Источник

Читайте также:  Calendar java android studio
Оцените статью