PHP: ocorrência de preg_replace (x)?
Fiz uma pergunta semelhante recentemente, mas não recebi uma resposta clara porque era muito específico. Este é mais amplo.
lguém sabe como substituir uma ocorrência (x) em um padrão rege
Exemplo: Digamos que eu queria substituir a 5ª ocorrência do padrão regex em uma string. Como eu faria isso
Aqui está o padrão:preg_replace('/{(.*?)\|\:(.*?)}/', 'replacement', $this->source);
@ anubhava CÓDIGO DE AMOSTRA SOLICITADO (a última função não funciona):
$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);
}
}