문제

Regex를 사용하여 태그에서 정보를 추출한 다음 태그의 여러 부분을 기반으로 결과를 반환하려고합니다.

preg_replace('/<(example )?(example2)+ />/', analyze(array($0, $1, $2)), $src);

그래서 나는 부품을 잡고 그것을 전달합니다 analyze() 기능. 그곳에 도착하면 부품 자체를 기반으로 작업하고 싶습니다.

function analyze($matches) {
    if ($matches[0] == '<example example2 />')
          return 'something_awesome';
    else if ($matches[1] == 'example')
          return 'ftw';
}

그러나 분석 기능에 도달하면 $matches[0] 단지 문자열과 같습니다. '$0'. 대신, 나는 필요합니다 $matches[0] preg_replace () 호출의 역전을 참조하십시오. 어떻게 할 수 있습니까?

감사.

편집 : 방금 preg_replace_callback () 함수를 보았습니다. 아마도 이것은 내가 찾고있는 것입니다 ...

도움이 되었습니까?

해결책

당신은 사용할 수 없습니다 preg_replace 그렇게. 당신은 아마 원할 것입니다 preg_replace_callback

다른 팁

$regex = '/<(example )?(example2)+ \/>/';
preg_match($regex, $subject, $matches);

// now you have the matches in $matches and you can process them as you want

// here you can replace all matches with modifications you made
preg_replace($regex, $matches, $subject);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top