PrimuS
PrimuS

Reputation: 2683

Replace two values in a preg_replace pattern

I have a regex that searches for occurences like this in a text:

to find

[pass id="HEH0Iu6rYl"][/pass]

Regex

preg_match_all('@\[pass id="(.*?)"\]\[\/pass\]@', $text, $matches);

For all the found $matches I lookup the "code" in my Database and if found I want to fill the password from the database so that the text looks like this: [pass id="HEH0Iu6rYl"]MYPASSWORD[/pass]

Function

preg_match_all('@\[pass id="(.*?)"\]\[\/pass\]@', $docPart->getText(), $matches);

foreach ($matches[1] as $key => $match) {

    /* Try to find existing Code and Update Password */
    $password = $this->getDoctrine()->getRepository('AppBundle:Password')->findOneBy(array(
        'code' => $match,
    ));

    /* Check if it s Users own Password or User is able via AccesGroup */
    if($aG->getCanPassword() === true || $password->getUser() === $this->getUser()){
            
        /* Update the text */
        $pwText = preg_replace('#(\]).*?(\[/pass])#', $password->getPass(), $docPart->getText());
    }
}

But then the replacement looks like this: [pass id="HEH0Iu6rYl"MYPASS How do I have to change the regex?

Upvotes: 0

Views: 112

Answers (1)

Toto
Toto

Reputation: 91428

Change to this:

$pwText = preg_replace('#(\]).*?(\[/pass])#', '$1'.$password->getPass().'$2', $docPart->getText());
//                                            ^^^^^                    ^^^^^

$1 contains the group 1 ie. ] and $2 contains [/pass]

Upvotes: 1

Related Questions