I have a html-string that contains multiple parts like this:
$source = '
<span id="pass_AwfpSYYUsn" data-id="AwfpSYYUsn" class="pointer unlockFieldChild" data-client="51" data-status="closed"><i class="fa fa-lock"></i> Show</span>
<!-- OTHER HTML STUFF -->
<span id="pass_DbTD7TjEDX" data-id="DbTD7TjEDX" class="pointer unlockFieldChild" data-client="51" data-status="closed"><i class="fa fa-lock"></i> Show</span>
';
I would like to replace all of those with this:
[pass id="AwfpSYYUsn"]PASSWORD OR EMPTY[/pass]
<!-- OTHER HTML STUFF -->
[pass id="DbTD7TjEDX"]PASSWORD OR EMPTY[/pass]
The data-client
and the data-id
is what I need for this
What I did
preg_match_all('@<span id="pass_(.*?)".*?data-client="(.*?)".*?</span>@', $content, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$pw = '';
/* This checks and fills the password, not really relvant to the question */
if ($aG->getCanPassword()) {
$p = $em->getRepository('AppBundle:PasswordList')->findOneBy(array(
'code' => $match[1],
));
if ($p !== null) {
$pw = $p->getPass();
}
}
$content = str_replace('<span id="pass_' . $match[1] . '" data-id="' . $match[1] . '" class="pointer unlockFieldChild" data-client="' . $match[2] . '" data-status="closed"><i class="fa fa-lock"></i> Show</span>', '[pass id="' . $match[1] . '"]' . $pw . '[/pass]', $content);
}
This works, but I don't really like the str_replace
approach, is there a way to do it in a (single) preg_replace
, possibly w/out the foreach?
Any hint appreciated!