What's the best way change link innertext? #817
Answered
by
colinodell
benfiratkaya
asked this question in
Q&A
-
Hello i coding my own extension for links. I want to change link text to url. My code working well but is this the best way? foreach ($e->getDocument()->iterator() as $link) {
if ($link_type === self::APPLY_NONE)
continue;
if (!($link instanceof Link))
continue;
$host = parse_url($link->getUrl(), PHP_URL_HOST);
if (!is_string($host)) {
// Something is terribly wrong with this URL
continue;
}
// Is this the best way??
$link->detachChildren();
$link->appendChild(new Text($link->getUrl()));
} |
Beta Was this translation helpful? Give feedback.
Answered by
colinodell
Feb 28, 2022
Replies: 1 comment
-
That looks pretty good to me! If you wanted to optimize this further you could do something like this: // Avoid iterating through the entire document if we already know we won't be doing anything
if ($link_type === self::APPLY_NONE)
return;
foreach ($e->getDocument()->iterator() as $link) {
if (!($link instanceof Link))
continue;
$host = parse_url($link->getUrl(), PHP_URL_HOST);
if (!is_string($host)) {
// Something is terribly wrong with this URL
continue;
}
// This does exactly the same thing you did under-the-hood. It isn't any faster or better, but it might be easier to understand:
$link->replaceChildren([new Text($link->getUrl())]);
} Nicely done! |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
benfiratkaya
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That looks pretty good to me! If you wanted to optimize this further you could do something like this:
Nicely done!