Question

J'essaie d'atteindre les objectifs suivants:

$ subject = 'a b a';
$ search = 'a';
$ remplace = '1';

Résultat souhaité:

Tableau
(
[0] = > 1 b a
    [1] = > a b 1
)

Existe-t-il un moyen de réaliser cela avec preg_replace?

preg_replace ('/ \ b'. $ search. '(? = \ s + | $) / u', $ remplacer, tableau ($ sujet));

renverra tous les remplacements dans le même résultat:

Tableau
(
    [0] = > 1 b 1
)

A bientôt

Était-ce utile?

La solution

Je pense que ce n'est pas possible. Vous pouvez spécifier une limite de remplacements dans le quatrième paramètre facultatif, mais cela commence toujours au début.

Il est possible de réaliser ce que vous recherchez avec preg_split () . Il vous suffira de scinder votre chaîne à toutes les occasions de votre modèle de recherche, puis de les manipuler une par une. Si votre modèle de recherche est juste une simple chaîne, vous pouvez obtenir la même chose avec explode () . Si vous avez besoin d’aide pour comprendre cette approche, je me ferai un plaisir de vous aider.

MODIFIER : voyons si cela fonctionne pour vous:

$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);

Remarque: ceci n'a pas encore été testé. Veuillez indiquer si cela fonctionne.

EDIT 2 :

Je l'ai testé avec votre exemple maintenant, j'ai corrigé quelques problèmes et tout fonctionne maintenant (du moins avec cet exemple).

Autres conseils

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'));

Sortie

Array
(
    [0] => 1 b a
    [1] => a b 1
)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top