Yeni giriş dizelerini oluşturmak için bir regex geri çalışma

1 Cevap php

Ben gibi normal bir ifade var:

/items\/a=(0-9)+\/b=(0-9)+/

gibi URL'ler hangi maçlar:

items/a=5/b=5, items/a=11/b=9 etc. (I hope the regex is correct, but please do not mind if it is not)

Ne yapmam mümkün istiyorum geri bu regexp içine değerleri enjekte yüzden değerleri için a = 99, b = 99 var diyelim ve ben dize öğeleri / a = 99 / b = 99 çalışmak istiyorum. Bu string işlemleri ile elle yapılabilir ama regex desen kendisini kullanarak bunu yapmak için bir yolu var mı?

The reason I want to do this is I am trying to write a routing method for a front controller. Assuming I match the url /product/3 to controller = ProductController, action = display, id=3 I want to be able to create the url back using a function createUrl($controller, $action, $params) from the regex.

Ben açık olduğunu umuyoruz, benim İngilizce bu konuda çok üzgünüm çok iyi değil.

1 Cevap

Evet, ifade içindeki her grup için offset bulmak ve sonra (dizenin sonundan başlayarak) belirli kayıklıklarında altdizgelerin eklemek gerekir

    $re = '/items\/a=([0-9])+\/b=([0-9])+/';
    $str = 'items/a=5/b=6';

    $replacements = array(1 => 123, 2 => 456);

    preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE); 

    for($i = count($matches) - 1; $i > 0; $i--) {
        $p = $matches[$i];
        $str = substr_replace($str, $replacements[$i], $p[1], strlen($p[0]));
    }