PHP:preg_replace(x)发生?

kr1*_*zmo 3 php regex

我最近问了一个类似的问题,但没有得到一个明确的答案,因为我太具体了.这个更广泛.

有谁知道如何在正则表达式模式中替换(x)出现?

示例:假设我想替换字符串中第5次出现的正则表达式.我该怎么办?

这是模式: preg_replace('/{(.*?)\|\:(.*?)}/', 'replacement', $this->source);

@anubhava请求的示例代码(最后一个函数不起作用):


$sample = 'blah asada asdas  {load|:title} steve jobs {load|:css} windows apple ';


$syntax = new syntax();
$syntax->parse($sample);


class syntax {

    protected $source;
    protected $i;
    protected $r;

        // parse source
    public function parse($source) {
                // set source to protected class var
        $this->source = $source;

        // match all occurrences for regex and run loop
        $output = array();
        preg_match_all('/\{(.*?)\|\:(.*?)\}/', $this->source, $output);

                // run loop
        $i = 0;
        foreach($output[0] as $key):
            // perform run function for each occurrence, send first match before |: and second match after |:
            $this->run($output[1][$i], $output[2][$i], $i);

            $i++;
        endforeach;

        echo $this->source;

    }

        // run function
    public function run($m, $p, $i) {
                // if method is load perform actions and run inject
        switch($m):

            case 'load':
                $this->inject($i, 'content');
            break;

        endswitch;

    }

        // this function should inject the modified data, but I'm still working on this.
    private function inject($i, $r) {

          $output = preg_replace('/\{(.*?)\|\:(.*?)\}/', $r, $this->source);

    }


}


Kei*_*han 8

你误解了正则表达式:它们是无状态的,没有记忆,没有能力计数,没有,所以你不能知道匹配是字符串中的第x个匹配 - 正则表达式引擎没有线索.你不能做这种事情有出于同样的原因正则表达式,因为它不是可以写一个正则表达式来看看一个字符串具有平衡括号:这个问题需要存储器,其中,顾名思义,正则表达式不具备的.

但是,正则表达式引擎可以告诉您所有匹配项,因此您最好使用preg_match()获取匹配项列表,然后自己使用该信息修改字符串.

更新:这更接近你的想法吗?

<?php
class Parser {

    private $i;

    public function parse($source) {
        $this->i = 0;
        return preg_replace_callback('/\{(.*?)\|\:(.*?)\}/', array($this, 'on_match'), $source);
    }

    private function on_match($m) {
        $this->i++;

        // Do what you processing you need on the match.
        print_r(array('m' => $m, 'i' => $this->i));

        // Return what you want the replacement to be.
        return $m[0] . '=>' . $this->i;
    }
}

$sample = 'blah asada asdas  {load|:title} steve jobs {load|:css} windows apple ';
$parse = new Parser();
$result = $parse->parse($sample);
echo "Result is: [$result]\n";
Run Code Online (Sandbox Code Playgroud)

这使...

Array
(
    [m] => Array
        (
            [0] => {load|:title}
            [1] => load
            [2] => title
        )

    [i] => 1
)
Array
(
    [m] => Array
        (
            [0] => {load|:css}
            [1] => load
            [2] => css
        )

    [i] => 2
)
Result is: [blah asada asdas  {load|:title}=>1 steve jobs {load|:css}=>2 windows apple ]
Run Code Online (Sandbox Code Playgroud)

  • +1所以_thats_你怎么做`preg_replace_callback()`oop方式!我刚刚学到了新的感谢! (2认同)