我最近问了一个类似的问题,但没有得到一个明确的答案,因为我太具体了.这个更广泛.
有谁知道如何在正则表达式模式中替换(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):
// …Run Code Online (Sandbox Code Playgroud)