题
我试图实现如下:
$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));
将返回所有replacments中相同的结果:
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