CakeFest 2024: The Official CakePHP Conference

preg_replace_callback_array

(PHP 7, PHP 8)

preg_replace_callback_arrayGeriçağırım kullanarak düzenli ifade arama ve değiştirmesi yapar

Açıklama

preg_replace_callback_array(
    array $şablon,
    string|array $konu,
    int $sınır = -1,
    int &$sayı = null,
    int $seçenekler = 0
): string|array|null

Her şablon için ayrı bir geriçağırım işlevi çağrılması dışında preg_replace_callback() işlevi gibidir.

Bağımsız Değişkenler

şablon

Şablonların (anahtarlar) geriçağırım işlevlerine (değerler) eşleştirildiği bir dizi.

konu

Şablonun aranacağı yer değiştirmeye konu dizge veya dizi.

sınır

Her konu dizgesinde her şablon için olası azami yer değiştirme sayısı. -1 öntanımlıdır (sınırsız).

sayı

Belirtildiği takdirde yapılan yer değiştirmelerin sayısı bu bağımsız değişkene konur.

seçenekler

seçenekler bağımsız değişkeni, eşleşen dizinin biçimini açıklamak için PREG_OFFSET_CAPTURE ve PREG_UNMATCHED_AS_NULL seçeneklerini bir arada içerebilir. Ayrıntılar preg_match() işlevinde bulunabilir.

Dönen Değerler

konu bağımsız değişkeni bir dizi ise işlev bir dizi, dizge ise bir dizge döndürür. Hata durumunda null döner.

Eşleşme gerçekleşmişse yeni konu, aksi takdirde konu değiştirilmeden döndürülür.

Hatalar/İstisnalar

Düzenli ifade şablonu derlendiğinde geçerli bir düzenli ifade haline gelmezse bir E_WARNING çıktılanır.

Sürüm Bilgisi

Sürüm: Açıklama
7.4.0 seçenekler bağımsız değişkeni eklendi.

Örnekler

Örnek 1 - preg_replace_callback_array() örneği

<?php
$subject
= 'Aaaaaa Bbb';

preg_replace_callback_array(
[
'~[a]+~i' => function ($match) {
echo
'"a" için ', strlen($match[0]), ' eşleşme bulundu', PHP_EOL;
},
'~[b]+~i' => function ($match) {
echo
'"b" için ', strlen($match[0]), ' eşleşme bulundu', PHP_EOL;
}
],
$subject
);
?>

Yukarıdaki örneğin çıktısı:

"a" için 6 eşleşme bulundu
"b" için 3 eşleşme bulundu

Ayrıca Bakınız

add a note

User Contributed Notes 3 notes

up
10
Sz.
6 years ago
Based on some tests, I found these important traits of the function. (These would
be nice to see documented as part of its spec, e.g. for confirmation. Without that,
this is just experimental curiosity. Still better than guesswork, though! ;) )

1. Changes cascade over a subject across callbacks, i.e. a change made to a
subject by a callback will be seen by the next callback, if its pattern matches
the changed subject.
(But a change made by a previous call of the *same* callback (on any subject)
will not be seen by that callback again.)

2. The pattern + callback pairs will be applied in the order of their appearance
in $patterns_and_callbacks.

3. The callback can't be null (or '') for a quick shortcut for empty replacements.

4. Overall, the algorithm starts iterating over $patterns_and_callbacks, and then
feeds each $subject to the current callback, repeatedly for every single match
of its pattern on the current subject (unlike "preg_match_all", that is, which
can do the same in one go, returning the accumulated results in an array).

This basically means that the "crown jewel", an even more efficient function:
"preg_replace_all_callback_array" is still missing from the collection.

(Of course, that would better fit a new design of the regex API, where one
API could flexibly handle various different modes via some $flags = [] array.)

5. (This last one is not specific to this function, but inherent to regexes, OTOH,
it's probably more relevant here than anywhere else in PHP's regex support.)

Even apparently simple cases can generate a crazy (and difficult-to-predict)
number of matches, and therefore callback invokations, so remember the set
$limit, where affordable. But, of course, try to sharpen your patterns first!

E.g. use ^...$ anchoring to avoid unintended extra calls on matching substrings
of a subject, (I.e. '/.*/', without anchoring, would match twice: once for the
whole subject, and then for a trailing empty substring -- but I'm not quite sure
this should actually be correct behavior, though.)
up
9
drevilkuko at gmail dot com
8 years ago
finally!!!

before (<=php5.6):

<?php
$htmlString
= preg_replace_callback(
'/(href="?)(\S+)("?)/i',
function (&
$matches) {
return
$matches[1] . urldecode($matches[2]) . $matches[3];
},
$htmlString
);

$htmlString = preg_replace_callback(
'/(href="?\S+)(%24)(\S+)?"?/i', // %24 = $
function (&$matches) {
return
urldecode($matches[1] . '$' . $matches[3]);
},
$htmlString
);
?>

php7

<?php

$htmlString
= preg_replace_callback_array(
[
'/(href="?)(\S+)("?)/i' => function (&$matches) {
return
$matches[1] . urldecode($matches[2]) . $matches[3];
},
'/(href="?\S+)(%24)(\S+)?"?/i' => function (&$matches) {
return
urldecode($matches[1] . '$' . $matches[3]);
}
],
$htmlString
);
?>
up
-4
jfcherng at NOSPAM dot gmail dot com
8 years ago
Here's a possible alternative in older PHP.

<?php

// if (!function_exists('preg_replace_callback_array')) {

function preg_replace_callback_array (array $patterns_and_callbacks, $subject, $limit=-1, &$count=NULL) {
$count = 0;
foreach (
$patterns_and_callbacks as $pattern => &$callback) {
$subject = preg_replace_callback($pattern, $callback, $subject, $limit, $partial_count);
$count += $partial_count;
}
return
preg_last_error() == PREG_NO_ERROR ? $subject : NULL;
}

// }

?>
To Top