문제
다음을 달성하려고합니다.
$subject = 'a b a';
$search = 'a';
$replace = '1';
원하는 결과 :
Array
(
[0] => 1 b a
[1] => a b 1
)
preg_replace에서 이것을 달성하는 방법이 있습니까?
preg_replace('/\b'.$search.'(?=\s+|$)/u', $replace, array($subject));
동일한 결과에서 모든 교체를 반환합니다.
Array
(
[0] => 1 b 1
)
건배
해결책
나는 그것이 불가능하다고 생각합니다. 옵션 네 번째 매개 변수에서 교체 한계를 지정할 수 있지만 항상 시작부터 시작됩니다.
당신이 찾고있는 것을 달성하는 것이 가능할 수 있습니다. preg_split()
. 검색 패턴의 모든 경우에 문자열을 분할 한 다음 하나씩 엉망이됩니다. 검색 패턴이 간단한 문자열 인 경우 explode()
. 이 접근법을 알아내는 데 도움이 필요하면 기꺼이 도와 드리겠습니다.
편집하다: 이것이 당신에게 효과적인지 보자 :
$subject = 'a b a';
$pattern = '/a/';
$replace = 1;
// We split the string up on all of its matches and obtain the matches, too
$parts = preg_split($pattern, $subject);
preg_match_all($pattern, $subject, $matches);
$numParts = count($parts);
$results = array();
for ($i = 1; $i < $numParts; $i++)
{
// We're modifying a copy of the parts every time
$partsCopy = $parts;
// First, replace one of the matches
$partsCopy[$i] = $replace.$partsCopy[$i];
// Prepend the matching string to those parts that are not supposed to be replaced yet
foreach ($partsCopy as $index => &$value)
{
if ($index != $i && $index != 0)
$value = $matches[0][$index - 1].$value;
}
// Bring it all back together now
$results[] = implode('', $partsCopy);
}
print_r($results);
참고 : 이것은 아직 테스트되지 않았습니다. 그것이 작동하는지보고하십시오.
편집 2:
나는 지금 당신의 예제로 그것을 테스트하고 몇 가지를 수정했으며 지금은 작동합니다 (적어도 그 예에서).
다른 팁
function multipleReplace($search,$subject,$replace) {
preg_match_all($search, $subject,$matches,PREG_OFFSET_CAPTURE);
foreach($matches as $match) {
if (is_array($match)) {
foreach ($match as $submatch) {
list($string,$start) = $submatch;
$length = strlen($string);
$val = "";
if ($start - 1 > 0) {
$val .= substr($subject,0,$start);
}
$val .= preg_replace($search,$string,$replace);
$val .= substr($subject,$start + $length);
$ret[] = $val;
}
}
}
return $ret;
}
$search = 'a';
print_r(multipleReplace('/\b'.$search.'(?=\s+|$)/u','a b a','1'));
산출
Array
(
[0] => 1 b a
[1] => a b 1
)
제휴하지 않습니다 StackOverflow